Skip to main content
 首页 » 编程设计

python之Python 的文件名约定

2025年05月04日41lyhabc

为什么我必须在“black.txt”文件名前加一个额外的反斜杠,而不是在“planet.txt”文件名前加一个反斜杠?

“b”和“p”有什么区别?它不适用于以其他字符(例如“a”)开头的文件名。

 open('C:\Python27\MyScripts\\black.txt') 

这是我在“black.txt”之前不使用两个反斜杠时得到的错误:

Traceback (most recent call last): 
  File "C:\Python27\MyScripts\script5.py", line 2, in <module> 
    f = open('C:\Python27\MyScripts\black.txt') 
IOError: [Errno 22] invalid mode ('r') or filename: 
'C:\\Python27\\MyScripts>\x08lack.txt' 

请您参考如下方法:

这是因为"\b" is a Python escape character .也就是说,一旦处理成字符串,它就变成了另一个字符。

来自documentation :

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

...

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C

“\p”不是转义字符,因此 Windows 上的 Python 会自动为您转换反斜杠(显然,虽然我找不到相关文档)。

在 Python interpreter prompt在 Windows 上:

>>> a = "\b" 
>>> a 
'\x08' 
>>> b = "\p" 
>>> b 
'\\p' 

如果您编写的代码可能会被其他人使用,您应该考虑 portability .所以在写路径的时候,应该使用os.path.join :

在 Windows 上:

>>> import os 
>>> os.path.join('path', 'to', 'file') 
'path\\to\\file' 

在 *nix 上

>>> import os 
>>> os.path.join('path', 'to', 'file') 
'path/to/file' 

如果您有其他一些普通 字符串文字,为了安全起见,请始终使用双反斜杠。除非你使用 raw strings, which don't do the escape character replacement (见第一段)。