tags:

views:

97

answers:

4

I'm looking to translate the unix-command

$ cat filename.* > Datei

into a Python program. Can somebody help ?

+2  A: 

Something like this should get you started:

import glob

outfile = file("Datei", "wb")
for f in glob.glob("filename.*"):
  infile = open(f, "rb")
  outfile.write(infile.read())
  infile.close()
outfile.close()

UPDATE: Of course, input files need to be opened, too.

UPDATE: Explicitly use binary mode.

unwind
You forgot to `open()` your input files. `glob.glob` does return a list of file names, not file objects.
Ferdinand Beyer
for binary files is better to do out.write(open(f).read())
Ferran
For portability, you should also open your files with in binary mode ('rb', 'wb'). Nasty things will happen on Windows otherwise.
Ferdinand Beyer
`in` is a keyword.
jleedev
@Ferdinand, @Ferran: Thanks, fixed!
unwind
+1  A: 
import glob

output = open('Datei', 'wb')
chunk_size = 8192
for filename in glob.glob('filename.*'):
    input = open(filename, 'rb')
    buffer = input.read(chunk_size)
    while buffer: # False if buffer == ""
        output.write(buffer)
        buffer = input.read(chunk_size)
    input.close()
output.close()
Ferdinand Beyer
This might be more efficient than `readlines` since it doesn't have to scan for newline characters.
jleedev
A: 

alternatively

import os
f=open("outfile.txt","a")
for file in os.listdir("."):
    if file.startswith("filename."):
         for line in open(file):
               f.write(line)
f.close()
A: 

Thank you for your help. My script now:

LOGFILEDIR="/olatfile/logs"
VORMONAT=time.strftime("%Y-%m", time.localtime(time.time()-3600*24*30))
LOGDATEIEN=LOGFILEDIR+"/olat.log."+VORMONAT +"-*"
print LOGDATEIEN
OUTPUT=LOGFILEDIR+"/olat.log."+VORMONAT
LOGFILE=OUTPUT
output = open(OUTPUT, 'wb')
chunk_size = 8096
for filename in glob.glob(LOGDATEIEN):
input = open(filename, 'rb')
buffer = input.read(chunk_size)
while len(buffer) > 0:
output.write(buffer)
buffer = input.read(chunk_size)
input.close()
output.close()

An application create everyday a logfile like "olat.log.07-12-2009" My idea was to cat all the logs from one moth into one logfile and analyze this one.

Michael Jabs