Python TypeError:通过Windows CMD运行时强制使用Unicode
您好,我的脚本在通过CMD运行时出现了下一个错误,但它在MVS调试程序中成功运行Python TypeError:通过Windows CMD运行时强制使用Unicode,python,file,Python,File,您好,我的脚本在通过CMD运行时出现了下一个错误,但它在MVS调试程序中成功运行 Traceback (most recent call last): File "D:\Work\PyLineCounter\PyLineCounter\PyLineCounter\PyLineCounter.py", line 22, in <module> file = open(file_path,'rb') TypeError: coercing to Unicode: need s
Traceback (most recent call last):
File "D:\Work\PyLineCounter\PyLineCounter\PyLineCounter\PyLineCounter.py", line 22, in <module>
file = open(file_path,'rb')
TypeError: coercing to Unicode: need string or buffer, WindowsPath found
您使用的Python版本尚不支持在
open()
函数调用中使用pathlib
path对象。你只能这样做
你可以:
- 升级到Python 3.6或更新版本
- 使用
将路径转换为字符串,以便str()
打开(str(文件路径),'rb')
- 使用而不是
函数open()
- 使用,而不是手动打开和读取数据
for file_path in Path(PATH).rglob('*.h'):
raw_data = file_path.read_bytes()
但是,这确实需要Python3.5或更高版本。这已经是一个相当古老的版本了。如果您使用的是Python3.4,那么您确实需要升级,因为该版本不再获得任何支持
但是,如果您坚持使用Python 3.4,那么请使用Path.open()
:
请注意,使用
file=open(…)
,使用file
,file.close()
作为上下文管理器更好地处理,因此使用open(…)作为file:
,(新缩进级别),使用file
执行一些操作,然后让with
语句为您关闭文件对象。我在上面的Path.open()
示例中使用了该模式。感谢您提供完整的答案。但是转换到str在我的cas中不起作用。
for file_path in Path(PATH).rglob('*.h'):
raw_data = file_path.read_bytes()
for file_path in Path(PATH).rglob('*.h'):
with file_path.open('rb'):
raw_data = file_path.read_bytes()