Skip to main content
 首页 » 编程设计

python之路径名中的编码字符

2024年11月24日798°冷暖

我使用的是 Python 版本:2.7.12 |Anaconda 4.1.1(64 位)| (默认,2016 年 6 月 29 日,11:07:13)[MSC v.1500 64 位 (AMD64)] (Windows 7)

我在脚本中使用 lz4,但在使用 lz4.frame.open() 读取文件时遇到问题

文件名来自 PyQt4 的选择文件对话框,并在调用 lz4.frame.open() 之前使用 encoding='utf-8' 转换为 unicode:

C:/Users/user/Desktop/δθμ/PREVIEW/Questionnaire.db 
<type 'unicode'> 

如果代码运行为

#fl = fl.encode('utf-8') 
 with lz4.frame.open(fl, mode='r') as f: 

我得到一个

    'filename must be a str, bytes, file or PathLike object' 
TypeError: filename must be a str, bytes, file or PathLike object 

如果代码运行为

fl = fl.encode('utf-8') 
with lz4.frame.open(fl, mode='r') as f: 

我得到一个

    self._fp = builtins.open(filename, mode) 
IOError: [Errno 2] No such file or directory: 'C:/Users/user/Desktop/\xce\xb4\xce\xb8\xce\xbc/PREVIEW/Questionnaire.db' 

错误。

知道如何解决这个问题吗?

编辑 1: 这不是重复的。正如我提到的,filedialog 返回的字符串在函数调用之前已使用 unicode(fl, 'utf-8') 转换为 unicode,但在这种情况下或在使用 'utf- 编码为 str 之后它会给出错误8'。你提到的链接中的问题是对话框返回的字符串没有像它应该的那样对待 qstring 类型

编辑 2: 如果将“δθμ”更改为拉丁字符,代码将按预期运行

fl = fl.encode('utf-8') 
with lz4.frame.open(fl, mode='r') as f: 

但必须处理包含此类字母甚至空格的文件夹。

请您参考如下方法:

错误提示:文件名必须是 str、bytes、file 或 PathLike 对象:

if sys.version_info > (3, 6): 
    path_test = isinstance(filename, (str, bytes, os.PathLike)) 
else: 
    path_test = isinstance(filename, (str, bytes)) 

我使用这段代码创建了源文件:

FL = u"δθμ.txt" 
DATA = open(r"source.js", "rb").read() 
LZ4_DATA = lz4.frame.compress(DATA) 
 
# write compressed data to a file 
with open(FL, "wb") as _file: 
    _file.write(LZ4_DATA) 

然后我给了他一个文件对象的实例:

# read compressed data from a file 
with open(FL, "rb") as _file: 
    with lz4.frame.open(_file) as f: 
        print(f.read()) 

而且有效。