windows上的python文件名 [英] python filename on windows
问题描述
免责声明我有一个类似的帖子,但我认为它太大了,太复杂了
Disclaimer I have a similar thread started but I think it got too big and convoluted
简而言之,这就是问题
import imghdr
import os.path
....
image_type = imghdr.what(os.path.normpath(filename))
失败
IOError: [Errno 22] invalid mode ('rb') or filename: 'D:\\mysvn\\trunk\\Assets\\models\\character\\char1.jpg\r'
上述文件存在的地方
帮助?:D
推荐答案
文件名末尾有一个回车符\r
.这不是 Windows 文件名的有效字符,所以我怀疑文件名是否有效.
There is a carriage return character \r
at the end of the filename. That is not a valid character for a Windows filename, so I doubt the filename will work.
使用 .rstrip('\r')
删除它:
image_type = imghdr.what(os.path.normpath(filename.rstrip('\r')))
.rstrip()
从字符串的末尾删除字符,并且只删除您命名的集合中的字符.
.rstrip()
removes characters from the end of a string, and only those in the set that you name.
因为这是一个文件名,文件名周围的任何空格可能是不正确的,所以直接的 .strip()
也可以:
Since this is a filename, any whitespace around the filename is probably incorrect, so a straight-up .strip()
would work too:
image_type = imghdr.what(os.path.normpath(filename.strip()))
这会从字符串的开始和结尾删除制表符、换行符、回车符和空格.
This would remove tabs, newlines, carriage returns and spaces from both the start and end of the string.
这篇关于windows上的python文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!