Search code examples
python-2.7lines

Combine multiple lines of text documents into one


I have thousands of text documents and they have varied number of lines of texts. I want to combine all the lines into one single line in each document individually. That is for example:

abcd 
efgh 
ijkl

should become as

abcd efgh ijkl 

I tried using sed commands but it is quite not achieving what I want as the number of lines in each documents vary. Please suggest what I can do. I am working on python in ubuntu. One line commands would be of great help. thanks in advance!


Solution

  • If you place your script in the same directory as your files, the following code should work.

    import os
    count = 0
    for doc in os.listdir('C:\Users\B\Desktop\\newdocs'):
        if doc.endswith(".txt"):
            with open(doc, 'r') as f:
                single_line = ''.join([line for line in f])
                single_space = ' '.join(single_line.split())
    
            with open("new_doc{}.txt".format(count) , "w") as doc:
                doc.write(single_space)
            count += 1
        else:
            continue
    

    @inspectorG4dget's code is more compact than mine -- and thus I think it's better. I tried to make mine as user-friendly as possible. Hope it helps!