【发布时间】:2011-10-06 23:40:35
【问题描述】:
我处理大量未知文件,并且一直在学习 python 来帮助我过滤/排序和处理这些文件。
我正在查看的集合有大量资源分支,我编写了一个小脚本来查找它们并删除它们(下一步是找到它们并移动它们,但那是另一天的事了)。
我在这个集合中发现有许多文件名中包含非 ascii 字符,这似乎触发了 os.delete 函数。
示例文件名:._spec com 报告 395 (注意 3 在它下面有一个小点,我找不到示例,或者弄清楚如何显示文件名的十六进制...)
我记录了所有文件名,这是该文件的日志记录:._spec com report 3?95
我得到的错误是windowserror,因为它找不到文件(它传递的字符串不是windows操作系统所知道的文件。)我放入了一个try子句以允许我工作它,但我真的很喜欢妥善处理它。
我还尝试根据这篇文章在步行选项 `os.walk(u'.') 中使用 unicode 开关:Handling ascii char in python string(最佳答案),我看到以下错误:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "c:\python27\lib\encodings\cp850.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\uf022' in position
20: character maps to <undefined>
所以我猜答案在于如何解析文件名,并想知道是否有人能够指出我正确的方向......
代码:
import os
import sys
rootdir = "c:\target Dir to walk"
destKeep = "Keepers.txt"
destDelete = "Deleted.txt"
matchingText = "._"
files_removed = 1
for folder, subs, files in os.walk(rootdir):
outfileKeep = open(destKeep,"a")
outfileDelete = open(destDelete,"a")
for filename in files:
matchScore = filename.find(matchingText)
src = os.path.join(folder, filename)
srcNewline = src + ", " + str(filename) + "\n"
if matchScore == -1:
outfileKeep.writelines(srcNewline)
else:
outfileDelete.writelines(srcNewline)
try:
os.remove(src)
except WindowsError:
print "I was unable to delete this file:"
outfileKeep.writelines(srcNewline)
files_removed += 1
if files_removed:
print '%d files removed' % files_removed
else :
print 'No files removed'
outfileKeep.close()
outfileDelete.close()
【问题讨论】:
标签: python macos unicode filenames