如何在 Python 的 Linux 和 Windows 中使用“/”(目录分隔符)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16010992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use "/" (directory separator) in both Linux and Windows in Python?
提问by hulk007
I have written a code in python which uses / to make a particular file in a folder, if I want to use the code in windows it will not work, is there a way by which I can use the code in Windows and Linux.
我在 python 中编写了一个代码,它使用 / 在文件夹中创建一个特定的文件,如果我想在 Windows 中使用该代码它将无法工作,有没有办法可以在 Windows 和 Linux 中使用该代码。
In python I am using this code:
在python中我使用这个代码:
pathfile=os.path.dirname(templateFile)
rootTree.write(''+pathfile+'/output/log.txt')
When I will use my code in suppose windows machine my code will not work.
当我在假设 Windows 机器中使用我的代码时,我的代码将无法工作。
How do I use "/" (directory separator) in both Linux and Windows?
如何在 Linux 和 Windows 中使用“/”(目录分隔符)?
采纳答案by Serban Razvan
Use os.path.join()
.
Example: os.path.join(pathfile,"output","log.txt")
.
使用os.path.join()
. 例子:os.path.join(pathfile,"output","log.txt")
。
In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))
在您的代码中,这将是: rootTree.write(os.path.join(pathfile,"output","log.txt"))
回答by HymanPoint
Do a import os
and then use os.sep
做一个import os
然后使用os.sep
回答by Maroun
回答by Alexander Kononenko
Use:
用:
import os
print os.sep
to see how separator looks on a current OS.
In your code you can use:
查看分隔符在当前操作系统上的外观。
在您的代码中,您可以使用:
import os
path = os.path.join('folder_name', 'file_name')
回答by user151019
Don't build directory and file names your self, use python's included libraries.
不要自己构建目录和文件名,使用 python 包含的库。
In this case the relevant one is os.path. Especially join which creates a new pathname from a directory and a file name or directory and split that gets the filename from a full path.
在这种情况下,相关的是os.path。特别是 join 从目录和文件名或目录创建新路径名,并从完整路径中获取文件名。
Your example would be
你的例子是
pathfile=os.path.dirname(templateFile)
p = os.path.join(pathfile, 'output')
p = os.path.join( p, 'log.txt')
rootTree.write(p)
回答by Jon Rosen
os.path.normpath(pathname)
should also be mentioned as it converts /
path separators into \
separators on Windows. It also collapses redundant uplevel references... i.e., A/B
and A/foo/../B
and A/./B
all become A/B
. And if you are Windows, these all become A\B
.
os.path.normpath(pathname)
还应该提到,因为它将/
路径分隔符转换为\
Windows 上的分隔符。它还折叠了冗余的上级引用……即,A/B
并且A/foo/../B
和A/./B
都变成了A/B
。如果你是 Windows,这些都变成了A\B
.
回答by Eugene Yarmash
回答by P113305A009D8M
You can use "os.sep"
您可以使用“ os.sep”
import os
pathfile=os.path.dirname(templateFile)
directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
rootTree.write(directory)