以下代码用于整理当前文件夹。
import os, glob
print "Tidy up ScreenShot ..."
pwd = os.getcwd()
for file in glob.glob("*.png"):
#print file.encode('utf-8')
file_time = file.split(" ")
#print file_time[0]
file_times = file_time[0].split("-")
file_time_year = file_times[0]
file_time_month = file_times[1]
if (file_time_year.isdigit() and file_time_month.isdigit()):
#print file_time_year
#print file_time_month
target_dir = os.path.join(cwd, 'OLD', file_time_year, file_time_month)
if (not(os.path.exists(target_dir))):
os.makedirs(target_dir)
try:
os.rename(file, os.path.join(target_dir, file))
except WindowsError:
print "Error: %s" %file
通常它运行正常,但如果文件名中有一些特殊的章程,如中文,则会失败并显示以下错误消息:
Tidy up ScreenShot ...
Error: 2017-11-15 09_13_45-Download Windows 10 and 1 more page ?- Microsoft Edge.png
Error: 2017-11-17 14_14_48-IMG_20171117_141100.jpg ?- Photos.png
Error: 2017-11-17 14_36_18-IMG_20171117_143016.jpg ?- Photos.png
Error: 2017-11-17 16_18_17-IMG_20171117_161538.jpg ?- Photos.png
Error: 2017-12-05 17_40_29-Skype? .png
Error: 2017-12-06 12_37_37-No Permission - Inside and 1 more page ?- Microsoft Edge.png
Error: 2017-12-07 09_56_21-???Q16??_?????-?????_?????????_?????_????_?????.png
Error: 2017-12-07 09_58_23-???Q16??_?????-?????_?????????_?????_????_?????.png
Error: 2018-01-03 14_02_57-????????????????220v????????????-mall.com??.png
Error: 2018-01-03 14_03_39-????????????????220v????????????-mall.com??.png
Error: 2018-01-03 14_19_08-??R30??????????????????????????-mall.com??.png
如何解决这个问题?