如何从文件中删除行并将其移动到另一个文件中?

2024-04-23 12:12:09 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,文件包含:

apple,bot,cheese,-999
tea,fire,water,1
water,mountain,care,-999

所以我想检查文件1中的行的末尾是否有-999,如果有,请删除该行,然后将没有的行传输到新文件中。到目前为止,我的职能是:

def clean(filename,cleanfile,value,position):
filename.readline()
for line in filename:
    if line[position] != value:
        cleanfile.write(line)

值为-999,位置为3。我在main中打开文件并将其传递给函数,问题是新文件是空的。你知道吗


Tags: 文件applevaluebotlinepositionfilenamefire
2条回答

试试这个:

def clean(filename,cleanfile,value,position):
    for lines in filename.readlines():
        line = lines.strip().split(",")
        if line[position] != value:
            cleanfile.write(",".join(line) + "\n")

clean(open("readFrom.txt", "r"), open("writeTo.txt", "w"), "-999", 3) 

如果知道值始终位于每行的末尾,可以尝试:

def clean (file1, file2, value):
    for line in file1 :
        if line.strip().split(",")[-1] != value :
            file2.write(line)
    file1.close()
    file2.close()

clean(open("readFrom.txt", "r"), open("writeTo.txt", "w"), "-999") 

您可以使用csv模块来了解拆分和连接逗号分隔值的详细信息。你知道吗

import csv
def clean(filename,cleanfile,value,position):
    with open(filename) as reader_fp, open(cleanfile, 'w') as writer_fp:
        reader = csv.reader(reader_fp)
        writer = csv.writer(writer_fp)        
        for row in reader:
            if row[position] != value:
                writer.writerow(row)

相关问题 更多 >