我想根据列表在我的目录中编写一个现有的文件名,以便最终打开它。我知道我必须将字符串转换为有效的文件名,我想我会这样做,但显示以下错误:
IOError:[Errno 2]没有这样的文件或目录:' shapes-22-01-2015.log'
以下是代码:
for fileDate in sortList:
logfile = "shapes-" + fileDate + ".log"
print('Evaluating date ... ' + logfile)
with open('%s' %logfile, 'r') as inF:
答案 0 :(得分:1)
这里有两个选项:
您可以尝试打开该文件,看它是否存在,然后继续下一个文件:
import os
base_dir = '/path/to/directory'
for fileDate in sortList:
try:
with open(os.path.join(base_dir,
'shapes-{}.log'.format(fileDate)), 'r') as inF:
# do stuff with the file
except IOError:
print('Skipping {} as log file does not exist'.format(fileDate))
您可以直接获取与模式匹配的文件列表,然后阅读这些文件。这样你就可以保证文件存在(但是,如果例如另一个程序正在读取它,它可能仍然无法打开)。
import glob
pattern = 'shapes-*.log'
for filename in glob.iglob(os.path.join(base_dir, pattern)):
try:
with open(filename, 'r') as inF:
# do stuff with the file
except IOError:
print('Something went wrong, cannot open {}'.format(filename))
值得一提的是glob
将以随机顺序返回文件,它们不会被排序。如果您想先按日期对文件进行排序然后处理它们,您必须手动进行排序:
import datetime
date_fmt = '%d-%m-%Y'
def get_date(file_name):
return datetime.datetime.strptime(file_name.split('-', 1)[1], date_fmt)
files_by_date = sorted(glob.iglob(os.path.join(base_dir, pattern)),
key=get_date)
for filename in files_by_date:
# rest of the code here