0

Is there a way in Python to read in a txt file, remove the last 6 characters of each line and overwrite the old file with the same content just without the last 6 chars on each line?

I tried something like this:

with open(dat, "r+") as fp:
    for line in fp:
        line = line[:-6]
        fp.write(line+"\n")

But that only gives me a weird looking file with multiple entries and numbers at the wrong places.

Also

with open(dat, "r+") as fp:
    for line in fp:
        line = line[:-6]
        fp.write(line+"\n")

doesn't work. The whole file is empty when I am doing that.

Is there a smart way of doing this without doing the change, writing everything to a seperate file?

BallerNacken
  • 305
  • 7
  • 16

2 Answers2

1

You need to append the changed characters to a temporary list and then move the file pointer back to the beginning before writing again:

with open(dat, "r+") as fp:
    temp_list = []
    for line in fp:
        line = line[:-6]
        temp_list.append(line)
    fp.seek(0, 0)
    fp.write("\n".join(temp_list))

I hope this helps

Abdou
  • 12,931
  • 4
  • 39
  • 42
  • That works nearly. But for some reason it appends some of the data again at the end of the already corrected data. The extra appended data also still has the last 6 chars. Not sure whats going on. – BallerNacken Aug 09 '17 at 15:05
  • @BallerNacken, please make sure that you are replicating the code here properly. Also, try using `fp.seek(0, 0)` instead of just `fp.seek(0)`. Shouldn't make a difference, but give it a shot. – Abdou Aug 09 '17 at 15:23
1

Try the following code, which should help you:

with open(file,'r+') as fopen:
    string = ""
    for line in fopen.readlines():
        string = string + line[:-6] + "\n"

with open(file,'w') as fopen:
    fopen.write(string)
Fabien
  • 4,862
  • 2
  • 19
  • 33
Kantharaju
  • 11
  • 3