Home>Article>Backend Development> How to open the path of a file in python?

How to open the path of a file in python?

coldplay.xixi
coldplay.xixi Original
2020-06-10 17:22:10 25572browse

How to open the path of a file in python?

python怎么打开文件的路径?

python打开文件路径的方法:

1.我们知道用绝对路径打开一个文件。f=open('c:/Users/Administrator/Desktop/2.txt','r')。

How to open the path of a file in python?

2.这里要注意路径中的斜杠,和我们从文件属性中复制出来的方向不一致。这真是一个非常不方便的地方。那我们有没有方法解决呢?当然是有的。

How to open the path of a file in python?

3.我们设置一个路径变量。运行时成功的。

fpath = r'C:\Users\Administrator\Desktop\1.txt' with open(fpath, 'r') as f: s = f.read() print(s)

How to open the path of a file in python?

4.当然我们也可以不设置路径变量,而把路径放在open()方法里。运行也是成功的。

with open(r'C:\Users\Administrator\Desktop\1.txt', 'r') as f: s = f.read() print(s)

How to open the path of a file in python?

5.问题的关键在于路径前面的r,如果没有这个r,\就是转义符的作用,引起了路径错误。(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

How to open the path of a file in python?

6.

with open('C:\\a.txt', 'r') as f: s = f.read() print(s)

如果路径只有一个斜杠,则会报错。Traceback (most recent call last):

File "C:\Users\Administrator\Desktop\OneDrive\Python3.6.5\test.py", line 1, in

with open('C:\a.txt', 'r') as f:

OSError: [Errno 22] Invalid argument: 'C:\x07.txt'

有两个\\时表示的是一个\,路径就是正常的。这也是为什么需要/作为默认参数的原因。

How to open the path of a file in python?

The above is the detailed content of How to open the path of a file in python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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