如何使用"/" (目录分隔符)在Linux和Windows中都在Python中? [英] How to use "/" (directory separator) in both Linux and Windows in Python?
问题描述
我已经在python中编写了一个代码,该代码使用/在文件夹中创建特定文件,如果我想在Windows中使用该代码将无法正常工作,有没有一种方法可以在Windows中使用该代码并Linux.
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中,我正在使用以下代码:
In python I am using this code:
pathfile=os.path.dirname(templateFile)
rootTree.write(''+pathfile+'/output/log.txt')
假设我在Windows计算机中使用代码时,我的代码将无法工作.
When I will use my code in suppose windows machine my code will not work.
在Linux和Windows中如何使用"/"(目录分隔符)?
How do I use "/" (directory separator) in both Linux and Windows?
推荐答案
使用os.path.join()
.
例如:os.path.join(pathfile,"output","log.txt")
.
在您的代码中,该代码应为:rootTree.write(os.path.join(pathfile,"output","log.txt"))
In your code that would be: rootTree.write(os.path.join(pathfile,"output","log.txt"))
这篇关于如何使用"/" (目录分隔符)在Linux和Windows中都在Python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!