Python-将字符串转换为文件名
我想根据列表在我的目录中组合一个现有文件名,以便最终打开它。我知道我必须将字符串转换为有效的文件名,我想我是这样做的,但显示了以下错误: IOError:[Errno 2]没有这样的文件或目录:“shapes-22-01-2015.log” 代码如下:Python-将字符串转换为文件名,python,file-io,Python,File Io,我想根据列表在我的目录中组合一个现有文件名,以便最终打开它。我知道我必须将字符串转换为有效的文件名,我想我是这样做的,但显示了以下错误: IOError:[Errno 2]没有这样的文件或目录:“shapes-22-01-2015.log” 代码如下: for fileDate in sortList: logfile = "shapes-" + fileDate + ".log" print('Evaluating date ... ' + logfile)
for fileDate in sortList:
logfile = "shapes-" + fileDate + ".log"
print('Evaluating date ... ' + logfile)
with open('%s' %logfile, 'r') as inF:
这里有两个选项:
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))
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
与python目录相比,您的文件在哪里?您是否尝试过
logfile=“./shapes-”+fileDate+“.log”
或使用完整路径?我只是尝试了一下,它对我有效。您确定要在同一目录中执行脚本吗?尝试使用pwd bash命令并在open函数中使用路径,如下所示:open(“%s/%s%”(路径,日志文件),“r”)。你是对的,愚蠢的错误,我没有传递正确的目录。非常感谢。
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