我的目录中有大量 txt 文件E:\Desktop\Social_media\edit8\New folder (2)
,每个文件的排列如下:
Bolt;539,110
Classmates;263,454
PlanetAll;126,907
theGlobe;73,063
SixDegrees;64,065
JANUARY 1997
现在我想将最后一行移到第一行,如下所示:
JANUARY 1997
Bolt;539,110
Classmates;263,454
PlanetAll;126,907
theGlobe;73,063
SixDegrees;64,065
我为此编写了以下 python 脚本:
import os
directory = r'E:\Desktop\Social_media\edit8\New folder (2)' # Replace with the directory path containing your text files
# Get a list of all text files in the directory
files = [file for file in os.listdir(directory) if file.endswith('.txt')]
# Process each file
for file in files:
file_path = os.path.join(directory, file)
# Read the file content
with open(file_path, 'r') as f:
lines = f.readlines()
# Extract the last line and strip the newline character
last_line = lines.pop().strip()
# Insert the last line at the beginning
lines.insert(0, last_line)
# Write the modified content back to the file
with open(file_path, 'w') as f:
f.writelines(lines)
我的脚本运行良好,但我不知道为什么它将最后一行移动到第一行的第一行,如下所示:
JANUARY 1997Bolt;539,110
Classmates;263,454
PlanetAll;126,907
theGlobe;73,063
SixDegrees;64,065
我的脚本问题出在哪里?以及如何解决它?
您明确删除换行符
strip()
(注释如此)。去掉这条带子,应该就可以了。(strip
返回删除了前导和尾随空格字符的字符串副本 -文档)所以而不是
做
如果它不起作用或者您无法删除该
strip
方法,因为您实际上需要删除空格,您可以通过这样做在最后一行的末尾手动添加换行符