path = r'C:\Myfolder\data\today'
for root, directories, filenames in os.walk(path):
for filename in filenames:
fname = os.path.join(root,filename)
if os.path.isfile(fname) and fname[-4:] == '.log':
if fname not in rows1:
print fname
fname=fname.replace(path,"")
with open(fname, 'r') as myfile:
我的文件名看起来像C:\ Myfolder \ data \ today \ 00.log,我只需要"今天\ 00.log" 错误是IOError:[Errno 2]没有这样的文件或目录:' \ today \ 00.log' 如何从文件名中删除\?
答案 0 :(得分:-1)
此外,没有真正的错误,你不应该使用replace去掉已知的前缀,而是使用字符串切片并使用完整的文件名来打开文件:
path = r'C:\Myfolder\data\today'
for root, directories, filenames in os.walk(path):
for filename in filenames:
fullname = os.path.join(root,filename)
if os.path.isfile(fullname) and fullname[-4:] == '.log':
if fullname not in rows1:
print fullname
fname = fullname[len(path)+1:]
with open(fullname, 'r') as myfile:
do_something