如何使用“/"(目录分隔符)在 Python 中的 Linux 和 Windows 中? [英] How to use "/" (directory separator) in both Linux and Windows in Python?

查看:23
本文介绍了如何使用“/"(目录分隔符)在 Python 中的 Linux 和 Windows 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆