Punkster
Punkster

Reputation: 221

File append in python

I have n files in the location /root as follows

result1.txt
abc
def

result2.txt
abc
def
result3.txt
abc
def

and so on. I must create a consolidated file called result.txt with all the values concatenated from all result files looping through the n files in a location /root/samplepath.

Upvotes: 1

Views: 158

Answers (2)

Mickael_Paris
Mickael_Paris

Reputation: 37

That could be an easy way of doing so

Lets says for example that my file script.py is in a folder and along with that script there is a folder called testing, with inside all the text files named like file_0, file_1....

import os

#reads all the files and put everything in data
number_of_files = 0
data =[]
for i in range (number_of_files):
    fn = os.path.join(os.path.dirname(__file__), 'testing/file_%d.txt' % i) 
    f = open(fn, 'r')
    for line in f:
            data.append(line)
    f.close()


#write everything to result.txt
fn = os.path.join(os.path.dirname(__file__), 'result.txt')
f = open(fn, 'w')
for element in data:
    f.write(element)
f.close()

Upvotes: -1

Brobin
Brobin

Reputation: 3326

It may be easier to use cat, as others have suggested. If you must do it with Python, this should work. It finds all of the text files in the directory and appends their contents to the result file.

import glob, os

os.chdir('/root')

with open('result.txt', 'w+') as result_file:
    for filename in glob.glob('result*.txt'):
        with open(filename) as file:
            result_file.write(file.read())
            # append a line break if you want to separate them
            result_file.write("\n")

Upvotes: 3

Related Questions