Skip to content
Advertisement

Copying the first line in the .txt file and writing it to the last line Python

I have a txt file with 5 lines. I want to delete the first line copied after typing the text in the first line on the last line.

Example:

1
2
3
4
5

After:

2
3
4
5
1

my attempt

with open("equasisemail.txt", 'r') as file:
    data = file.read().splitlines(True)
with open ("equasisemail.txt",'w') as fi:
    fi.writelines(data[1:])

i use this to delete the first line.

Advertisement

Answer

read the lines using readlines (don’t splitlines else you lose line terminator). Then write back the file using writelines then write the final line with a simple write

with open("equasisemail.txt", 'r') as file:
    data = file.readlines()
# make sure the last line ends with newline (may not be the case)
if not data[-1].endswith("n"):
   data[-1] += "n"
with open ("equasisemail.txt",'w') as fi:
    fi.writelines(data[1:])
    fi.write(data[0])

careful as if something bad happens during the write the file is destroyed. Better use another name, then rename once writing has completed. In which case what can be done is reading & writing at almost the same time on 2 separate filenames:

with open("equasisemail.txt", 'r') as fr,open ("equasisemail2.txt",'w') as fw:
    first_line = next(fr)  # manual iterate to get first line
    for line in fr:
      fw.write(line)
    if not line.endswith("n"):
       fw.write("n")
    fw.write(first_line)
os.remove("equasisemail.txt")
os.rename("equasisemail2.txt","equasisemail.txt")

safer & saves memory. Fails if the file is empty. Test it first.

note: both solutions support files that don’t end with a newline character.

Advertisement