Python和Windows中的双反斜杠

-2 投票
1 回答
3054 浏览
提问于 2025-04-17 19:59

我在本地机器上运行了一个程序,这个程序需要用到一些文件。我是通过以下方式来创建文件的路径的:os.path.join( tempfile.gettempdir(), 'filename.txt' )

之后,我运行一个程序,这个程序需要一些参数,比如--log-file filepath,其中的filepath就是我刚才提到的文件路径。

在我的机器上,Python生成的路径是用反斜杠(\)来表示的,但不是双反斜杠(\\),这让程序很不高兴,因为它把单反斜杠当成了转义字符,应该用双反斜杠。

有没有什么标准的方法可以确保在Python中得到一个带有双反斜杠的有效路径呢?我可以用正则表达式,但我更希望用类似于os.提供的方式。也许我漏掉了什么。

我使用subprocess.Popen来调用这个程序:

self._proc = subprocess.Popen( command.split( ' ' ) )

其中command的内容类似于pcix.exe --log-file file_path

另外,在我的控制台上测试显示,Python并没有生成双反斜杠的路径:

>>> print os.path.join(tempfile.gettempdir(), "test.txt")
c:\users\manilo~1\appdata\local\temp\test.txt

如果不使用print命令,生成的路径也是一样的:

>>> os.path.join(tempfile.gettempdir(), "test.txt")
c:\users\manilo~1\appdata\local\temp\test.txt

这是什么原因呢?

附注:我运行的环境是CPython

1 个回答

-1

试试这个:

print os.path.join(tempfile.gettempdir(), "test.txt").replace('\\\\','\\\\\\\\')

撰写回答