-2

Can anyone give me some advice on creating a loop to cut the last 4 characters from every line within an input file?

I have tried:

myfile =  open('delete.txt', 'w+') 
myfile.read()
for line in myfile:
        line = line[:3]
       
myfile.close()

The file is formatted like thi:

Awks,1er,xyz,lon,thr,tkj,,^M
Atks,1er,xyz,lon,thr,toj,,^M
Ahks,1er,xyz,lon,thr,taj,,^M
Auks,1er,xaz,lon,thr,tej,,^M
Aqks,1er,xyz,lon,thr,twj,,,^M
Aoks,1er,xaz,lon,thr,twj,,^M
Apks,1er,xwz,lon,thr,trj,,^M
Alks,1er,xuz,lon,thr,toe,,^M
ssks,1er,xoz,lon,thr,toj,,^M
ssks,1er,xnz,lon,thr,tog,,,^M
Nishi K
  • 3
  • 1
  • 2
    You need to write back the data after you change it, and I'd suggest writing to a separate file, just in case... Oh, and it's `line[:-3]` to chop off the last three characters. – Ken Y-N Aug 19 '20 at 03:42
  • 3
    You actually have to modify the file, you haven't done that anywhere. The *safe* way to do this is to create a separate file that is a modified version of your original, and then at the end, delete the old one and re-name the new one if you must. – juanpa.arrivillaga Aug 19 '20 at 03:42

1 Answers1

0

As some comments said, it's probably safer to open up the input file and write output to a separate file.

Using a with block is handy, because you don't need to handle closing a file; your file is automatically closed at the end of the block.

I'd do something like this:

with open('input.txt', 'r') as infile:
    with open('output.txt', 'w') as outfile:
        for line in infile:
            outfile.write(line[:-5])
            outfile.write('\n')

The line[:-5] will remove the last five characters of each line, which is probably what you want since each line also contains a newline, so it removes the newline and four characters. We outfile.write('\n') because the newline was removed, and we want it back.

Taylor Reece
  • 486
  • 3
  • 14