This question is related to Python concatenate text files
I have a list of file_names
, like [\'file1.txt\', \'file2.txt\', ...].
I wou
Use input from fileinput module. It reads from multiple files but makes it look like the strings are coming from a single file. (Lazy line iteration).
import fileinput
files= ['F:/files/a.txt','F:/files/c.txt','F:/files/c.txt']
allfiles = fileinput.input(files)
for line in allfiles: # this will iterate over lines in all the files
print(line)
# or read lines like this: allfiles.readline()
If you need all the text in one place use StringIO
import io
files= ['F:/files/a.txt','F:/files/c.txt','F:/files/c.txt']
lines = io.StringIO() #file like object to store all lines
for file_dir in files:
with open(file_dir, 'r') as file:
lines.write(file.read())
lines.write('\n')
lines.seek(0) # now you can treat this like a file like object
print(lines.read())