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:

JavaScript

After:

JavaScript

my attempt

JavaScript

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

JavaScript

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:

JavaScript

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