Python中的Windows路径 [英] Windows path in Python

查看:322
本文介绍了Python中的Windows路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代表Windows目录(例如"C:\meshes\as")的最佳方法是什么?我一直在尝试修改脚本,但是它永远无法正常工作,因为我似乎无法正确找到目录,因为'\'充当转义符?

What is the best way to represent a Windows directory, for example "C:\meshes\as"? I have been trying to modify a script but it never works because I can't seem to get the directory right, I assume because of the '\' acting as escape character?

推荐答案

您可以始终使用:

'C:/mydir'

这在Linux和Windows中均有效. 其他可能性是

this works both in linux and windows. Other posibility is

'C:\\mydir'

如果您对某些名称有疑问,也可以尝试使用原始字符串文字:

if you have problems with some names you can also try raw string literals:

r'C:\mydir'

不过,最佳实践是使用os.path模块功能,这些功能始终为您的操作系统选择正确的配置:

however best practice is to use the os.path module functions that always select the correct configuration for your OS:

os.path.join(mydir, myfile)

在python 3.4中,您还可以使用 pathlib 模块.这等同于以上内容:

From python 3.4 you can also use the pathlib module. This is equivelent to the above:

pathlib.Path(mydir, myfile)

pathlib.Path(mydir) / myfile

这篇关于Python中的Windows路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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