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

How do I go into all text files in a directory and delete everything in them after the second space?

I have a directory like this:
All text files

Each text file has this information:

106 114 24 25 1 0
705 79 19 21 1 0
661 361 30 37 1 0
212 332 30 37 1 0
704 236 20 25 1 0
620 404 30 37 1 0
615 248 20 25 1 0
641 165 20 25 1 0
676 47 19 21 1 0

I am trying to write a script (windows 11) that goes into this directory, accesses each text file and deletes everything after the second space.

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

Basically, I want the new text files to be like this:

106 114
705 79
661 361
212 332
704 236
620 404
615 248
641 165
676 47

The script can be in python as well

>Solution :

import os

directory = '/path/to/directory'

for filename in os.listdir(directory):
    if filename.endswith('.txt'):
        with open(os.path.join(directory, filename), 'r+') as file:
            lines = file.readlines()
            file.seek(0)
            for line in lines:
                words = line.split()
                new_line = ' '.join(words[:2]) + '\n'
                file.write(new_line)
            file.truncate()

Replace /path/to/directory with the path to your directory

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