如何使用“/"(目录分隔符)在 Python 中的 Linux 和 Windows 中? [英] 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"))
这篇关于如何使用“/"(目录分隔符)在 Python 中的 Linux 和 Windows 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!