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,

Community
  • 1
  • 1

2 Answers2

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.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
  • 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. :( – JetMashKangaroo Apr 16 '14 at 08:03
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.

Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
  • 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`. – Tim Pietzcker Apr 16 '14 at 07:54