gulfy
gulfy

Reputation: 47

Convert all text files in directory to strings (each txt file becomes 1-line)

I have a folder containing several .txt files I want converted into strings.

I want to convert each of them to strings, the output being either 1 file containing a single line of text for each file or a combination of all source files into 1 file where each source file is just 1 line of text.

Is there a way to do this with glob or fnmatch using the following code:

open("data.txt").read().replace('\n', '')

Upvotes: 0

Views: 641

Answers (1)

Using your code, this creates "1 file containing a single line of text for each file":

import glob, os

myfolder = 'folder' # name of your folder containing `.txt

with open('data.txt', 'w') as outfile:
    for txtfile in glob.glob(os.path.join(myfolder,  "*.txt")):
        with open(txtfile, 'r') as f:
            outfile.write(f.read().replace('\n',''))

Upvotes: 1

Related Questions