簡體   English   中英

如何在python中從文件中刪除行

[英]How to delete line from the file in python

我有一個文件F,內容龐大,例如F = [1,2,3,4,5,6,7,8,9,...]。 所以我想循環遍歷文件F並刪除文件中所有包含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

您不能立即刪除文件中的行,因此必須創建一個新文件,將剩余的行寫入其中。 這就是“狼吞虎咽”的例子。

我不清楚您要修改的文件格式是什么。 我假設它看起來像這樣:

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()會帶來什么影響,但是我經常使用它,而且似乎不會造成任何問題。

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

我假設文件僅包含以分隔的整數

像這樣嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM