wie könnte man für glob ein try catch Block bauen:
Code: Alles auswählen
for file in glob(os.path.join(Path2files, "*.txt")):
Viele Grüße
Code: Alles auswählen
for file in glob(os.path.join(Path2files, "*.txt")):
mit hat geschrieben:Hallo,
wie könnte man für glob ein try catch Block bauen:Code: Alles auswählen
for file in glob(os.path.join(Path2files, "*.txt")):
Code: Alles auswählen
try:
for file in glob(os.path.join(Path2files, "*.txt")):
# tue was
except Exception, e:
print e
Da kapiere ich jetzt die Frage nicht. Was ist denn "schreiben". Der Block an sich sieht immer so aus wie oben. Ggf. kommt manchmal ein finally oder ein else dazu. Das kann man aber ja pauschal nicht sagen, da es auf die Logik des konkreten Problems ankommt.Und wie würde ein try catch Block für schreiben aussehen?
Code: Alles auswählen
#!/usr/bin/env python
import os
from glob import glob
def testTry(input_File, output_gffs_file_names):
for line in input_File:
# try ?
output_file_names[line].write('\t'.join(line) + '\n')
if __name__ == '__main__':
output__file_names = {}
input_File = []
# try ?
outputResHandle = open("results.txt", 'w')
# try ?
for line in open("inputFile.txt", 'r'):
line = line.rstrip().split(',')
input_File.append(line)
# try ?
outputResHandle.write(', '.join(input_File[0]) + '\n')
try:
for file in glob(os.path.join("../tests", "*.txt")):
fileNameOutput = os.path.splitext(file)[0] + "-results.txt"
temp = []
# try?
for line in open(file, 'r'):
line = line.rstrip().split('\t')
temp.append(line)
# try ?
output_file_names[file] = open(gffFileNameOutput, 'w')
except Exception, e:
print e
testTry(input_File[1:], output_file_names)
Code: Alles auswählen
>>> f = open("gibt_es_nicht.txt", "r")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
f = open("gibt_es_nicht.txt", "r")
IOError: [Errno 2] No such file or directory: 'gibt_es_nicht.txt'
Code: Alles auswählen
>>> try:
... f = open("gibt_es_nicht.txt", "r")
... except IOError:
... print "Schiefgegangen..."
Schiefgegangen...