我在E:\Desktop\Social_media\edit8\New folder
目录中有大量的txt文件,每个文件都有类似如下的排列:
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
的排列
I write following python script for this but I don't know why not working:个
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!')
Where is my script problem? and how to fix it problem?个