Python - Convert string to filename
我想根据列表在我的目录中编写一个现有的文件名,以便最终打开它。 我知道我必须将字符串转换为有效的文件名,我想我这样做但显示以下错误:
IOError:[Errno 2]没有这样的文件或目录:'shapes-22-01-2015.log'
这是代码:
1 2 3 4 | for fileDate in sortList: logfile ="shapes-" + fileDate +".log" print('Evaluating date ... ' + logfile) with open('%s' %logfile, 'r') as inF: |
你有两个选择:
您可以尝试打开该文件,查看它是否存在,然后继续下一个文件:
1 2 3 4 5 6 7 8 9 10 | 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)) |
您可以直接获取与模式匹配的文件列表,然后阅读这些文件。 这样你可以保证文件存在(但是,如果例如另一个程序正在读取它,它可能仍然无法打开)。
1 2 3 4 5 6 7 8 | 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)) |
值得一提的是,
1 2 3 4 5 6 7 8 9 10 | 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 |