I have high number of txt files in E:\Desktop\Social_media\edit8\New folder (2) directory and each file have an arrangement like following:
Bolt;539,110
Classmates;263,454
PlanetAll;126,907
theGlobe;73,063
SixDegrees;64,065
JANUARY 1997
Now I want to move last lines to first line like following:
JANUARY 1997
Bolt;539,110
Classmates;263,454
PlanetAll;126,907
theGlobe;73,063
SixDegrees;64,065
I write following python script for this:
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)
My script working good but I don’t know why it move last line to first of first line like following:
JANUARY 1997Bolt;539,110
Classmates;263,454
PlanetAll;126,907
theGlobe;73,063
SixDegrees;64,065
Where is my script problem? and how to fix it?
>Solution :
You’re explicitely removing the newline character with strip() (the comments says so). Remove this strip and it should do fine. (strip returns a copy of the string with both leading and trailing whitespaces characters removed – documentation)
So instead of
# Extract the last line and strip the newline character
last_line = lines.pop().strip()
Do
# Extract the last line and strip the newline character
last_line = lines.pop()
If it does not work or if you can’t delete the strip method because you actually need to remove whitesaces, you can manually add a newline character at the end of the last line by doing like that
# Insert the last line at the beginning
lines.insert(0, last_line + '\n')