简体   繁体   中英

How to delete line from the file in python

I have a file F, content huge numbers eg F = [1,2,3,4,5,6,7,8,9,...]. So i want to loop over the file F and delete all lines contain any numbers in file say 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

You can not immediately delete lines in a file, so have to create a new file where you write the remaining lines to. That is what chonws example does.

It's not clear to me what the form of the file you are trying to modify is. I'm going to assume it looks like this:

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

Something like this might work for you:

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)

I've never been clear on what the implications of doing an open() as a one-off are, but I use it pretty regularly, and it doesn't seem to cause any problems.

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

I'm assuming the file contains only integer numbers separated by ,

Something like this?:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM