Johny Johny - 6 months ago 8
Python Question

Python writing lines from list causes IndexError

I have been trying to think of a way to do the following:

A file is opened and read. The file contains the following

15;0
2;0


The lines are read, the first digit of the line replaces the second one and the first digit of the line is replaced by 0:

f = open("data.txt", "r+")

for line in f:
if line != "\n":
lineList = line.replace("\n", "").split(";")
lineList[1] = lineList[0]
lineList[0] = "0"
dataLine = lineList[0] + ";" + lineList[1]
f.write(dataLine)

f.close()


The issue occurs when writing the line to file. How can I write both lines at the end of the file and delete the first two lines? Thanks

Answer

The fastest way to implement the solution (and probably a more logically correct way) is to first read the contents of the file within one context manager and after that to write the processed data to the same file within another context manager:

data = list()
with open("data.txt", "r") as f:
    for line in f.readlines():
        if line != '\n':
            listLine = line.split(";")
            data.append("0;{}\n".format(listLine[0]))

with open('data.txt', 'w') as f:
    for line in data:
        f.write(line)

Also, you do not need the overhead of assigning different values to listLine list and then creating a data entry to write into your file. Just use straight ahead what you already have.

The downside of this method is memory usage - if your file will be bigger than your memory, you'll need another approach.

Comments