简体   繁体   中英

How to delete a line from a file in Python

I tried to use this: Deleting a line from a file in Python . I changed the code a bit to suit my purposes, like so:

def deleteLine():
    f=open("cata.testprog","w+")
    content=f.readlines()
    outp = []
    print(f.readline())
    for lines in f:
        print(lines)
        if(lines[:4]!="0002"):
        #if the first four characters of a line do not equal
            outp.append(lines)
    print(outp)
    f.writelines(outp)
    f.close()

The problem is that the entire file gets replaced by an empty string and outp is equal to an empty list. My file is not empty, and I want to delete the line that begins with "0002". Printing f.readline() gave me an empty string. Does anyone have any idea of how to fix it?

Thanks in advance,

You have opened file in wrong mode: "w+". This mode is used for writing and reading, but at first it is truncated. At first open file for reading. If it is not huge file read it into memory, convert there and save it by opening file in write mode.

You changed the file handling completely compared to the linked question. There, the file is first opened to read the content, closed and then opened to write the processed content. Here you open it and you first use f.readlines() , so all the data of the file is in content and the file pointer is at the end of the file.

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