Johny Johny - 2 years ago 76
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


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]


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 Source

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

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download