[Tutor] concatenating files
Jay Deiman
jay at splitstreams.com
Fri Feb 27 18:54:28 CET 2009
Bala subramanian wrote:
> Hai,
>
> I have file1.dat,file2.dat...file 300.dat in one directory. I want to
> concatenate all the files in a single file (total.dat) with a string
> "END" separating the file contents.
> my total.dat should be
> file1.dat contents
> END
> file2.dat contents
> END
> ----
> ----
> file300.dat.
>
> now i have another 400 such *.dat files in another directory whose
> contents i hve to append to "total.dat", how can i do this task. i need
> to do something like, updating the file total.dat without overwritting it.
>
> Thanks,
> Bala
This should about do it:
-------------------------------------
#!/usr/bin/env python
import sys , os , glob
startDir = ''
totalFile = '/path/to/total.dat'
if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
startDir = sys.argv[1]
else:
print 'Usage: %s <startdir>' % os.path.basename(sys.argv[0])
sys.exit(1)
tfh = open(totalFile , 'a')
for f in glob.glob(os.path.join(startDir , '*.dat')):
tfh.write('%s contents\n' % f)
tfh.write(open(f).read())
tfh.write('\nEND\n')
tfh.close()
-------------------------------------
All you have to do is set "totalFile" to your main output file and then
call the script as "scriptname.py /path/to/datfile/directory".
--
Jay Deiman
\033:wq!
More information about the Tutor
mailing list