Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move last lines to first line

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading