Skip to content

Commit c24b080

Browse files
committed
add 5.14 忽略文件名编码
1 parent 25e6dbc commit c24b080

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# 5.14 忽略文件名编码
2+
3+
## 问题
4+
5+
你想使用原始文件名执行文件的I/O操作,也就是说文件名并没有经过系统默认编码去解码或编码过。
6+
7+
## 解决方案
8+
9+
默认情况下,所有的文件名都会根据 `sys.getfilesystemencoding()` 返回的文本编码来编码或解码。比如:
10+
11+
```python
12+
>>> sys.getfilesystemencoding()
13+
'utf-8'
14+
>>>
15+
```
16+
17+
如果因为某种原因你想忽略这种编码,可以使用一个原始字节字符串来指定一个文件名即可。比如:
18+
19+
```python
20+
>>> # Wrte a file using a unicode filename
21+
>>> with open('jalape\xf1o.txt', 'w') as f:
22+
... f.write('Spicy!')
23+
...
24+
6
25+
>>> # Directory listing (decoded)
26+
>>> import os
27+
>>> os.listdir('.')
28+
['jalapeño.txt']
29+
30+
>>> # Directory listing (raw)
31+
>>> os.listdir(b'.') # Note: byte string
32+
[b'jalapen\xcc\x83o.txt']
33+
34+
>>> # Open file with raw filename
35+
>>> with open(b'jalapen\xcc\x83o.txt') as f:
36+
... print(f.read())
37+
...
38+
Spicy!
39+
>>>
40+
```
41+
42+
正如你所见,在最后两个操作中,当你给文件相关函数如 `open()``os.listdir()` 传递字节字符串时,文件名的处理方式会稍有不同。
43+
44+
## 讨论
45+
46+
通常来讲,你不需要担心文件名的编码和解码,普通的文件名操作应该就没问题了。 但是,有些操作系统允许用户通过偶然或恶意方式去创建名字不符合默认编码的文件。 这些文件名可能会神秘地中断那些需要处理大量文件的Python程序。
47+
48+
读取目录并通过原始未解码方式处理文件名可以有效的避免这样的问题, 尽管这样会带来一定的编程难度。
49+
50+
关于打印不可解码的文件名,请参考5.15小节。

0 commit comments

Comments
 (0)