1

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.

Punkster
  • 221
  • 6
  • 17

2 Answers2

3

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")
Brobin
  • 3,241
  • 2
  • 19
  • 35
  • what if i have other txt files in the directory. If i use this glob then all the txt files will be concatenated ? – Punkster Jun 30 '15 at 14:56
  • 1
    If you only want files with the `result` keyword in them, do `glob.glob('result*.txt')`. – Brobin Jun 30 '15 at 14:56
-1

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()
Brobin
  • 3,241
  • 2
  • 19
  • 35