Python中的Windows路径

问题:Python中的Windows路径

例如,代表Windows目录的最佳方法是什么"C:\meshes\as"?我一直在尝试修改脚本,但是它永远无法正常工作,因为我似乎无法正确获得目录,我想是因为它'\'充当转义符?

What is the best way to represent a Windows directory, for example "C:\meshes\as"? I have been trying to modify a script but it never works because I can’t seem to get the directory right, I assume because of the '\' acting as escape character?


回答 0

您可以始终使用:

'C:/mydir'

这适用于linux和Windows。其他可能性是

'C:\\mydir'

如果您对某些名称有疑问,也可以尝试使用原始字符串文字:

r'C:\mydir'

但是,最佳实践是使用os.path始终为您的操作系统选择正确配置的模块功能:

os.path.join(mydir, myfile)

从python 3.4开始,您还可以使用pathlib模块。这等同于以上内容:

pathlib.Path(mydir, myfile)

要么

pathlib.Path(mydir) / myfile

you can use always:

'C:/mydir'

this works both in linux and windows. Other posibility is

'C:\\mydir'

if you have problems with some names you can also try raw string literals:

r'C:\mydir'

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

pathlib.Path(mydir, myfile)

or

pathlib.Path(mydir) / myfile

回答 1

使用os.path模块。

os.path.join( "C:", "meshes", "as" )

或使用原始字符串

r"C:\meshes\as"

我也建议不要在路径或文件名中使用空格。您可以在字符串中使用双反斜杠。

"C:\\meshes\\as.jpg"

Use the os.path module.

os.path.join( "C:", "meshes", "as" )

Or use raw strings

r"C:\meshes\as"

I would also recommend no spaces in the path or file names. And you could use double backslashes in your strings.

"C:\\meshes\\as.jpg"

回答 2

是的,\在Python中,字符串文字表示转义序列的开始。在您的路径中,您有一个有效的两个字符的转义序列\a,该序列被折叠成一个字符,即ASCII Bell

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

其他常见的转义序列包括\t(制表符),\n(换行),\r(回车):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

如您所见,在所有这些示例中,反斜杠和文字中的下一个字符被组合在一起以在最终字符串中形成单个字符。Python的转义序列的完整列表在这里

有多种解决方法:

  1. Python将不会处理与前缀字符串文字的转义序列rR

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Windows上的Python也应处理正斜杠。

  3. 您可以使用os.path.join

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. …或较新的pathlib模块

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a, which is collapsed into one character that is ASCII Bell:

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python’s escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. … or the newer pathlib module

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

回答 3

使用PowerShell

在Windows中,只要将PowerShell用作命令行界面,就可以/在所有地方像Linux或macOS一样在路径中使用。它预装在Windows上,并且支持许多Linux命令,例如lscommand。

如果使用Windows命令提示符(cmd在Windows“开始”菜单中键入时显示的命令提示符),则需要在其中指定路径\。您可以/在所有其他地方使用路径(代码编辑器,Python交互模式等)。

Use PowerShell

In Windows, you can use / in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls command.

If you use Windows Command Prompt (the one that appears when you type cmd in Windows Start Menu), you need to specify paths with \ just inside it. You can use / paths in all other places (code editor, Python interactive mode, etc.).


回答 4

如果您想粘贴其他来源的Windows路径(例如,文件资源管理器),则可以通过input()python控制台中的调用来粘贴:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

然后复制结果

In case you’d like to paste windows path from other source (say, File Explorer) – you can do so via input() call in python console:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

Then just copy the result