简体   繁体   中英

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.

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.

To edit a file without creating a new file you can save the contents of the file to main memory, then open it in write mode:

input = open("email.txt", "r")
lines = input.readlines()
input.close()

output = open("email.txt", "w")
for i in range(1, len(lines)):
    output.write(lines[i].strip() + "\n")
output.write(lines[0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM