Python 如何处理目录和文件名中的特殊字符?
以下代码用于整理当前文件夹Python 如何处理目录和文件名中的特殊字符?,python,filesystems,Python,Filesystems,以下代码用于整理当前文件夹 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
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
正常情况下,它运行正常,但如果文件名中有一些特殊的特许,如中文,它将失败,并显示以下错误消息:
整理屏幕截图。。。
错误:2017-11-15 09_13_45-下载Windows 10和更多页面?-Microsoft Edge.png
错误:2017-11-17 14_14_48-IMG_20171117_141100.jpg?-Photos.png
错误:2017-11-17 14_36_18-IMG_20171117_143016.jpg?-Photos.png
错误:2017-11-17 16_18_17-IMG_20171117_161538.jpg?-Photos.png
错误:2017-12-05 17_40_29-Skype。巴布亚新几内亚
错误:2017-12-06 12_37_37-无权限-内部和1页以上?-Microsoft Edge.png
错误:2017-12-07 09第16季度png
错误:2017-12-07 09\u 58\u 23-?Q16\uu?????????????????????????????????????????????????????????????????????????png
错误:2018-01-03 14_02_57-???220v???????mall.com???.png
错误:2018-01-03 14\u 03\u 39-???220v???????mall.com???.png
错误:2018-01-03 14_19_08-
如何解决此问题?您需要搜索与您的字母类型匹配的编码。所以普通英语/德语/。。。“普通特殊字符”强制在终端上进行UTF-8编码和转换——或者,如果您需要为unicode设置所需的一切,也可以。google上有大量的解决方案,所以请玩得开心。尝试将文件名转换为unicode:
file=file.decode('utf-8')
我建议更改除WindowsError之外的,以便您可以实际看到引发的异常,甚至可能无法捕获它,从而导致整个应用程序崩溃。只有一个文件名不能提供太多信息。@BłażejMichalik现在报告:回溯(最近一次调用):File=File.decode('utf-8')文件“C:\Python27\lib\encodings\utf_8.py”,第16行,在decode-return-codecs.utf_decode(输入,错误,真)UnicodeDecodeError:“utf8”编解码器无法解码位置25处的字节0x99:无效开始byte@RickRongen:删除后,除了:回溯(上次调用):文件“tidy.py”,第25行,在os.rename(文件,os.path.join(target_dir,File))WindowsError:[错误123]文件名、目录名或卷标语法不正确