如何从文件中删除行

时间:2015-01-17 06:49:23

标签: python

我试图用他的号码删除一行 代码示例

f = open("x.txt","r")
line = f.read()
f.close()
print line

结果是

test1
test
test2
test3

现在我可以按行号1或文件中的任何行删除test1

2 个答案:

答案 0 :(得分:1)

你可以这样试试:

def delete_lines(in_file, out_file, lines=None):
    with open(in_file) as f, open(out_file) as f1:
        for i,x in enumerate(f):
            if i+1 not in lines:
                f1.write(x)
delete_lines('in_file', 'out_file', [1])  # or you pass any line number

答案 1 :(得分:1)

您可以尝试使用此脚本,将行号放在列表中,然后删除它们,确保将文件与脚本放在同一目录中。

f = open('1.txt',"r")
lines = f.readlines()
f.close()
f = open('1.txt',"w")
lines_del=[2,3]#the number of lines to be deleted
for number,line in enumerate(lines):
    if number+1 not in lines_del :
        f.write(line)
f.close()