删除包含数字键序列的特定行 python
delete a specific line that includes a key sequence of numbers python
我有以下数据文件,我想删除第一列中包含“30”数字的整行。这个号码一直有这个位置。
我想的是读取文件并用第一列创建一个列表
并检查列表中的每个项目是否都存在这个数字“30”,然后根据索引删除整行。
但是我不确定如何进行。
请告诉我你的想法。
Datafile
以下是我到目前为止所做的尝试:
f = open("file.txt","r")
lines = f.readlines()
f.close()
f = open("file.txt","w")
for line in lines:
if line!="30"+"\n":
f.write(line)
f.close()
f = open("file.txt", "r")
lines = f.readlines()
f.close()
f = open("file.txt", "w")
for line in lines:
if '30' not in line[4:6]:
f.write(line)
f.close()
试试这个
如果您愿意使用 pandas,您可以分三行完成:
import pandas as pd
# Read in file
df = pd.read_csv("file.txt", header=None, delim_whitespace=True)
# Remove rows where first column contains '30'
df = df[~df[0].str.contains('30')]
# Save the result
df.to_csv("cleaned.txt", sep='\t', index=False, header=False)
可以轻松扩展此方法以执行其他类型的过滤或处理数据。
你可以做的一种方法是使用在开头捕获 30 的正则表达式是这样的:
import re
f = open("file.txt", "r")
lines = f.readlines()
f.close()
f = open("file.txt", "w")
for line in lines:
if re.search(r'^\d*30',line):
f.write(line)
f.close()
希望效果好。
我有以下数据文件,我想删除第一列中包含“30”数字的整行。这个号码一直有这个位置。
我想的是读取文件并用第一列创建一个列表 并检查列表中的每个项目是否都存在这个数字“30”,然后根据索引删除整行。
但是我不确定如何进行。
请告诉我你的想法。
Datafile
以下是我到目前为止所做的尝试:
f = open("file.txt","r")
lines = f.readlines()
f.close()
f = open("file.txt","w")
for line in lines:
if line!="30"+"\n":
f.write(line)
f.close()
f = open("file.txt", "r")
lines = f.readlines()
f.close()
f = open("file.txt", "w")
for line in lines:
if '30' not in line[4:6]:
f.write(line)
f.close()
试试这个
如果您愿意使用 pandas,您可以分三行完成:
import pandas as pd
# Read in file
df = pd.read_csv("file.txt", header=None, delim_whitespace=True)
# Remove rows where first column contains '30'
df = df[~df[0].str.contains('30')]
# Save the result
df.to_csv("cleaned.txt", sep='\t', index=False, header=False)
可以轻松扩展此方法以执行其他类型的过滤或处理数据。
你可以做的一种方法是使用在开头捕获 30 的正则表达式是这样的:
import re
f = open("file.txt", "r")
lines = f.readlines()
f.close()
f = open("file.txt", "w")
for line in lines:
if re.search(r'^\d*30',line):
f.write(line)
f.close()
希望效果好。