我的目录中有大量 txt 文件E:\Desktop\Social_media\edit8\New folder
,每个文件的排列类似于以下内容:
Bolt
2,739,393
Classmates
1,267,092
SixDegrees
1,077,353
PlanetAll
552,488
theGlobe
437,847
OpenDiary
9,251
1998
MARCH
034+
现在我想合并每个 txt 文件的最后 3 行,如下所示:
Bolt
2,739,393
Classmates
1,267,092
SixDegrees
1,077,353
PlanetAll
552,488
theGlobe
437,847
OpenDiary
9,251
034+ MARCH 1998
这意味着最后 3 行必须有这样的排列number+ month year
我为此编写了以下 python 脚本,但我不知道为什么不起作用:
import os
# Define the directory where your text files are located
directory_path = r'E:\Desktop\Social_media\edit8\New folder'
# Function to rearrange the lines and write to a new file
def rearrange_lines(file_path):
with open(file_path, 'r') as file:
lines = [line.strip() for line in file.readlines() if line.strip()] # Read non-empty lines
# Check if there are at least 3 non-empty lines
if len(lines) >= 3:
lines[-1], lines[-2], lines[-3] = lines[-3], lines[-2], lines[-1] # Rearrange the last 3 lines
# Create a new file with the rearranged lines
with open(file_path, 'w') as file:
file.write('\n'.join(lines))
# Iterate through each file in the directory
for root, dirs, files in os.walk(directory_path):
for file_name in files:
if file_name.endswith('.txt'):
file_path = os.path.join(root, file_name)
rearrange_lines(file_path)
print(f'Rearranged lines in {file_name}')
print('Done!')
我的脚本问题出在哪里?以及如何解决这个问题?
您没有将结果中的最后 3 行合并为一行。
分配给
lines[-3:]
是切片替换。我们用单行列表替换它。我在评论的帮助下发现了我的脚本的问题: