FileNotFoundError: [Errno 2] No such file or directory, mapped drive, Python

1.7k views Asked by At

I am new to both Linux and Python, so I may not be correct in my terminology and understanding of the environment, but I am just trying to open a file on a network share and can't seem to get it right.

I created the folder ~/NAS_2 on a Raspberry Pi and mapped it to a share on my NAS using an entry in fstab. The ls command and results show that the file exists and is visible from the Pi while logged on with the pi account, which is a member of root.

pi@PI-0W-02: ~ $ ls -ld ~/NAS_2
drwxrwxrwx 52 root root 0 Oct  9 08:56 /home/pi/NAS_2

There is a file in the share named setup_info.txt.

pi@PI-0W-02: ~ $ ls ~/NAS_2/setup_info.txt
/home/pi/NAS_2/setup_info.txt

When I try to open the file from Python using the code below, I get the error following the Python code snippet.

>>> file_object  = open("~/NAS_2/setup_info.txt", "w")
FileNotFoundError: [Errno 2] No such file or directory: '~/NAS_2/setup_info.txt'

If I use the code that follows, Python seems happy to open the file.

>>> os.chdir("NAS_2")
>>> file_object  = open("setup_info.txt", "w")

Obviously, this is Python 101 stuff, but I can’t see why it should take 2 steps to open the file, and I’d rather not have to worry about any side effects of using chdir in a script. Is there some way to include the path in the open command, or am I stuck using it?

Thanks in advance for any help you can offer.

1

There are 1 answers

0
kendfss On

If I understand, your problem is that your python is unable to locate/complete a relative path. If that is so, and 'home/pi' points to a directory named 'pi' in your file system's root, you may want:

import os
dir_path = os.path.join(os.path.expanduser('~'),'pi','NAS_S')
file_path = os.path.join(dir_path,'setup_info.txt')

Or whatever it is that the full path looks like, instead of:

dir_path = "~/NAS_S"
file_path = "~/NAS_S/setup_info.txt"

If this works, it's because Python doesn't know how to handle '~' at the start of a path. and/or Your python script/instance is not running out of the root directory.

Alternatively you could use glob

import glob, os

file_name = 'blah.ext'
glob.glob(os.path.join(os.path.expanduser('~'),'*blah.ext')) ## a list of files that match the search pattern

To get more out of glob see the docs on it, as well as those for fnmatch for more on pattern syntax