0

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,

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I put that in for debugging, but I didn't realise it put the pointer at the end of the file. Thank you. I would vote up, but I do not have the reputation. :(
1

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.

1 Comment

Also, a file can only be iterated over once. So the line content = f.readlines() needs to be removed, especially since nothing is being done with content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.