Concatenating files in order

Mahmood Naderan nt_mahmood at yahoo.com
Tue May 23 17:14:34 EDT 2017


OK guys thank you very much. It is better to sort them first.


Here is what I wrote

files =  glob.glob('*chunk*')
sorted=[[int(name.split("_")[-1]), name] for name in files]
with open('final.txt', 'w') as outf:
      for fname in sorted:
            with open(fname[1]) as inf:
       for line in inf:
         outf.write(line)
 

and it works
Regards,
Mahmood


On Wednesday, May 24, 2017 1:20 AM, bartc <bc at freeuk.com> wrote:



On 23/05/2017 20:55, Rob Gaddi wrote:

> Yup.  Make a list of all the file names, write a key function that
> extracts the numbery bits, sort the list based on that key function, and
> go to town.

Is it necessary to sort them? If XXX is known, then presumably the first 
file will be called XXX_chunk_0, the next XXX_chunk_1 and so on.

It would be possible to iterate over such a sequence of filenames, and 
keep opening them then writing them to the output until there are no 
more files. Or, if a list of matching files is obtained, the length of 
the list will also give you the last filename.

(But this won't work if there are gaps in the sequence or the numeric 
format is variable.)

-- 
bartc

-- 
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list