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

时间:2014-11-22 00:02:02

标签: python python-3.x

好的,所以文件包含:

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中打开文件并将其传递给函数,问题是新文件为空。

3 个答案:

答案 0 :(得分:1)

您可以使用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)

答案 1 :(得分:0)

试试这个:

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) 

答案 2 :(得分:0)

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

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")