lotus
lotus

Reputation: 111

How to find the all text files from the path and combine all the lines in that text files to one text file

I have this code to combine all lines from one text file and combine it into one line in another new text file. For example: i have a text file with these lines

College

Escape

Power

Text

And i need to combine these lines into on line as

College Escape Power Text

This is working fine for me.

Code:

import os
current = None 
parts = []
with open('input.txt', 'rb') as f:
    for line in f:
        if line.startswith('--'):
            current = [line.strip()]
            parts.append(current)

        elif current is not None:
             current.append(line.strip())


with open('output.txt', 'w+b') as f1:
 for part in parts:
    f1.write('\n'+' '.join(part+' '))

But need to combine the all text file lines into one text file.Can you please guide me for this.

Example:I have these text files in my path.

  1. input.txt

  2. input (1).txt

  3. input (2).txt

  4. input (3).txt

Upvotes: 0

Views: 62

Answers (1)

srowland
srowland

Reputation: 1705

You can read in all the text files like this:

import os

file_contents = []
for file in os.listdir("directory_to_search"):
    if file.endswith(".txt"):
        with open('input.txt', 'rb') as f:
            file_contents.append(" ".join(line.strip() for line in f))

This will populate file_contents with the contents of each file, so now you can write them all to the output file:

with open('output.txt', 'w+b') as f1:
    all_files_as_one_string = ' '.join(file_contents)
    f1.write(all_files_as_one_string)

Note that if there is more than one word in each of your files, you will need to loop through the file_contents list and join all the lines up before you make the single big string from them.

Upvotes: 1

Related Questions