Home > Backend Development > Python Tutorial > Discuss in detail the file path problem of python in windows

Discuss in detail the file path problem of python in windows

不言
Release: 2018-04-28 09:54:51
Original
2094 people have browsed it

下面为大家分享一篇详谈python在windows中的文件路径问题,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

在使用python通过open()函数来打开文件的时候,传递绝对路径给open()的时候,发现路径参数的内容与想象中的有所出入:

由于windows的路径分隔符使用的是反斜杠\,它刚刚好是转义字符,故可能发生冲突

# 错误示范:反斜杠似乎被解释为转义字符而不是分隔字符
path = '''F:\Python\test.txt'''    
path = '''F:\\Python\test.txt'''

"""以下三种方式都是可行的"""
path = '''F:\Python\\test.txt'''
path = '''F:\\Python\\test.txt'''
path = '''F:\Python\\test.txt'''    
'''绝对路径的最后一个反斜杠使用了双反斜杠时就正常'''
'''原因是最后一个反斜杠可以与它紧挨着的字符t构成转义效果'''
Copy after login

结论:使用绝对路径的时候,要注意在绝对路径中使用的反斜杠与它后面紧跟着的字符会不会构成转义效果,如果会产生转义效果,如\t \n \r等等,则必须使用双反斜杠来取消单反斜杠的转义效果。如果产生了转义字符带来的错误,会出现open()提示 "Invalid arguments"

相关推荐:

分析python在不同层级目录import模块的方法

Python在groupby分组后提取指定位置记录方法

The above is the detailed content of Discuss in detail the file path problem of python in windows. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template