简体   繁体   中英

Accessing local file in python

I am using python 3.6. I want to access the file E:\\all_study\\python\\Bearing_fault.mat . This is not in the home directory. I have tried open("\\E:\\all_study\\python\\Bearing_fault.mat","r") command, but it is not working!

Escape the backslashes, because its a special character. and remove the backslash before E

open("E:\\all_study\\python\\Bearing_fault.mat","r")

Try pathlib, it'll help with trouble shooting. Note the forward slashes in this example. That'll work with open() as well.

from pathlib import Path

p = Path('E:/all_study/python/Bearing_fault.mat')

print(p.exists())
print(p.is_file())
print(p.read_text())

with p.open() as f:
    f.read_line()

Alternatively, prefixing the string with r disables escaping allowing direct pasting of the path.

p = Path(r'E:\all_study\python\Bearing_fault.mat')

But here's the main reason for pathlib. If the file is in the same directory as the script, leverage that to improve portability and reliability. (Could easily be adapted to support scenario where the file is in a different directory to python script)

p = Path(__file__).with_name('Bearing_fault.mat')
>>> print("\E:\all_study\python\Bearing_fault.mat")
\E:ll_study\python\Bearing_fault.mat

It's no surprise that path doesn't exist! Every backslash in the string literal is being parsed for escape sequences, such as \\a for alert which produces a bell character . In addition, you don't put backslashes in front of drive letters. You can disable the escape sequences for a particular literal using raw strings :

>>> print(r"E:\all_study\python\Bearing_fault.mat")
E:\all_study\python\Bearing_fault.mat

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM