简体   繁体   English

复制 .txt 文件中的第一行并将其写入最后一行 Python

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

I have a txt file with 5 lines.我有一个 5 行的 txt 文件。 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).使用readlines读取行(不要拆分行,否则会丢失行终止符)。 Then write back the file using writelines then write the final line with a simple write然后使用writelines写回文件,然后用简单的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:在这种情况下,可以做的是几乎同时读取和写入 2 个单独的文件名:

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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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