如何在python中删除文件中的行

时间:2011-09-10 13:48:07

标签: python

我有一个文件F,内容很大,例如F = [1,2,3,4,5,6,7,8,9,...]。所以我想循环遍历文件F并删除所有行包含文件中的任何数字,例如f = [1,2,4,7,...]。

F = open(file)
f = [1,2,4,7,...]
for line in F:
    if line.contains(any number in f):
        delete the line in F

4 个答案:

答案 0 :(得分:3)

您无法立即删除文件中的行,因此必须创建一个新文件,将剩余的行写入。这就是chonws的例子。

答案 1 :(得分:1)

我不清楚您要修改的文件形式是什么。我假设它看起来像这样:

1,2,3
4,5,7,19
6,2,57
7,8,9
128

这样的事可能适合你:

filter = set([2, 9])
lines = open("data.txt").readlines()
outlines = []
for line in lines:
    line_numbers = set(int(num) for num in line.split(","))
    if not filter & line_numbers:
        outlines.append(line)
if len(outlines) < len(lines):
    open("data.txt", "w").writelines(outlines)

我从来都不清楚open()作为一次性的含义是什么,但我经常使用它,它似乎没有引起任何问题。

答案 2 :(得分:1)

exclude = set((2, 4, 8))           # is faster to find items in a set
out = open('filtered.txt', 'w')
with open('numbers.txt') as i:     # iterates over the lines of a file
    for l in i:
        if not any((int(x) in exclude for x in l.split(','))):
            out.write(l)
out.close()

我假设文件只包含由

分隔的整数

答案 3 :(得分:0)

这样的东西?:

nums = [1, 2]
f = open("file", "r")
source = f.read()
f.close()
out = open("file", "w")
for line in source.splitlines():
    found = False
    for n in nums:
        if line.find(str(n)) > -1:
            found = True
            break
    if found:
        continue
    out.write(line+"\n")
out.close()