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

Question:

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.

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

Answers:

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

This should work:

import os

DIR = '/path'

for listed_file in os.listdir(DIR):
    if listed_file.endswith(".txt"):
        with open(listed_file, 'r') as file:
            final_lines = []
            for line in file.readlines():
                new_line = " ".join(line.split()[:2]) + "n"
                final_lines.append(new_line)
        file = open(listed_file, 'w')
        file.writelines(final_lines)

it will run through each and every file in DIR, check if it is a txt file and then get its lines and rewrite it with the new split lines.

Answered By: Noft
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.