Python: absolute path error in mac - python

I am using python on mac and would like to open a pdf file that is present in different directory than the directory my main python code is running. I tried different options but there is always an error saying file doesn't exist even when the file is present or [Error no. 2] file cannot be opened. Here is the code that I use:
helpFile = os.path.abspath('~/help/help.pdf')
self.help_btn = tk.Button(self.help_frm, text="Help!", width=8, command = lambda: os.system("open "+helpFile))
could some one help please.

abspath does not expand ~ into the user's home directory, it just calculates the absolute path of a file based on its path relative to the current working directory.
From the docs, it is equivalent to:
normpath(join(os.getcwd(), path))
So in your code, helpFile is being set to "/path/to/cwd/~/help/help.pdf"
To expand ~, use os.path.expanduser.

Related

Not finding any solution to [Errno 2]

I'm trying to use a program to read from a file with pi-digits. The program and the text file with the pi-digits are in the same directory, but i still get the error message :
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
Traceback (most recent call last):
File "C:\Python\Python_Work\python_crash_course\files_and_exceptions\file_reader.py", line 1, in <module>
with open('pi_digits.txt') as file_object:
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
I have looked for a solution but haven't found any.
I found a piece of code which supposedly shows me what the working directory is. I get an output that shows a directory that is 2 steps above the directory i have my programs and text file inside.
import os
cwd = os.getcwd() # Get the current working directory (cwd)
files = os.listdir(cwd) # Get all the files in that directory
print("Files in %r: %s" % (cwd, files))
So when i put the pi text document in the directory that the output is showing (>python_work), the program is working. When it does not work is when the text file is in ">files_and_exceptions" which is the same file the program itself is inside. My directory looks like this when it is not working:
>python_work
>python_crash_course
>files_and_exceptions
file_reader.py
pi_digits.txt
show_working_directory.py
And like this when it is working:
>python_work
pi_digits.txt
>python_crash_course
>files_and_exceptions
file_reader.py
show_working_directory.py
I'm new to python and really appreciate any help.
Thanks!
Relative path (one not starting with a leading /) is relative to some directory. In this case (and generally*), it's relative to the current working directory of the process.
In your case, given the information you've provided, for it would be "python_crash_course/files_and_exceptions/pi_digits.txt" in the first case as you appear to be running the script from python_work directory.
If you know the file to be in the same directory as the script itself, you could also say:
import os.path
...
os.path.join(os.path.dirname(__file__), "pi_digits.txt")
instead of "pi_digits.txt". Or the same using pathlib:
from pathlib import Path
...
Path(__file__).with_name("pi_digits.txt")
Actually unless you have a point to anchor to like the script itself, using relative filename / path (using absolute paths brings its own problems too) in the code directly is rather fragile and in that case getting it as a parameter of a function (and ultimately argument of CLI or script call in general) or alternatively reading it from standard input would be more robust.
* I would not make that an absolute statement, because there are situations and functions that can explicitly provide different anchor point (e.g. os.path.relpath or openat(2); or as another example a symlink target)

How to set relative path properly (in Python)?

I'm trying to set a path to an icon in my project.
"/icons/currency/USD.png"
But I'm getting an error:
FileNotFoundError: [Errno 2] No such file or directory: 'icons/currency/USD.png'
If I set the path to "/icons/USD.png"
everything is work.
but I don't want all my icons will be in one folder so I open currency folder
to separate it from other icons.
my project folders structure is:
project folder -> name_of_project.py , icons folder
icons folder -> currency folder -> USD.png
What is the correct way to configure this relative path ?
I'd recommend using os.path.join() to get full paths without bothering with your OS's specifics.
Currently you are setting your path to start from the root of your OS (I'm assuming Linux because of the path you have given as example). What you need is to get the path (absolute) of the file you are running and navigating from there.
You can do it as follows:
abs_path_of_executable_file = os.path.split(os.path.abspath(__file__))[0]
path_to_png = os.path.join(abs_path_of_executable_file, 'icons', 'currency', 'USD.png')
# do stuff with path_to_png
Where the first line gets the absolute path of the file you are executing (os.path.abspath(__file__)) and then you are taking the full path of the directory containing that file (os.path.split('some/path/to/file.py')[0]).
os.path.split('some/path/to/file.py')[1] gives you only the filename, without any paths.

What is the pythonic way to get file handles from the command line with relative or absolute paths?

When I write a command line script in python, I'm assuming that it can be invoked from anywhere. This seems to cause incongruity when I want to pass a list of files into the script.
Passing the files using a list or wildcard arguments (whether expanded by bash under *nix or glob.glob with Windows) will return either a relative path or an absolute one, depending on how the file path was described, but this seems to give two different behaviors which have to either be checked or harmonized.
If the script is in the same directory as the files to be imported, this isn't really a problem, but if the script is in a different directory, it seems like you need to grab the absolute path first:
import os,sys,glob
for arg in sys.argv[1:]:
file_list = glob.glob(arg)
for fn in file_list:
print("File Reference: {}".format(os.path.abspath(fn)))
> pwd
/Users/user1/Desktop/script_dir/
> cd ~/Desktop
> script_dir/test.py test_dir/*.csv /Users/user1/Desktop/test_dir/*.txt
File Reference: /Users/user1/Desktop/test_dir/temp1.csv
File Reference: /Users/user1/Desktop/test_dir/temp2.csv
File Reference: /Users/user1/Desktop/test_dir/temp1.txt
File Reference: /Users/user1/Desktop/test_dir/temp2.txt
Assuming the program continued on to do something with the files, it would then manipulate them by absolute path. Is this the correct thing to do here? It seems weirdly klugy, and I can seem to find any references that lay this out.

How to load dependencies and subfolders in Pycharm?

I am so new with python and pycharm and i got confuse!!
When I run my project in pycharm it gives me an error about not finding the path of my file. The physical file path is:
'../Project/BC/RequiredFiles/resources/a_reqs.csv'
My project working directory is "Project/BC" and the project running file (startApp.sh) is there too. but the .py file that wants to work with a_req.csv is inside the "RequiredFiles" folder. There is the following code in the .py file:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
it returns: '../Project/BC/resources/a_reqs.csv'
instead of: '../Project/BC/resources/RequiredFiles/a_reqs.csv'
while the .py file is in "RequiredFiles" the os.getcwd() must include it too. but it does not.
The problem is that i can not change the addressing code. because this code works in another IDE and other people who work with the code in other platform or OS do not have any problem. I am working in mac OS and if i am not mistaken the code works with windows!!
So, how can i tell Pycharm (in mac) to see and load "RequiredFiles" folder as the subfolder of my working directory!!!
os.getcwd returns the current working directory of the process (which may be the directory where startApp.sh is located or another one, depending on the PyCharm's run configuration setting, or, if you start the program from the command line, the directory in which you execute the command).
To make a path independent on the current working directory, you can take the directory where your Python file is located and build the path from it:
os.path.dirname(__file__) + "/resources/a_reqs.csv"
From your question what I see is:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
Which produces: "../Project/BC/resources/a_reqs.csv", whereas your desired output is
"../Project/BC/resources/RequiredFiles/a_reqs.csv". Since we know os.getcwd is returning "/Project/BC/", then to get your desired result you should be doing:
reqsfile = os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"
But since you want the solution to work with or without the RequiredFiles subdirectory you could apply a conditional solution, ie something like:
import os.path
if os.path.exists(os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"):
reqsfile = os.getcwd() + "/resources/RequiredFiles/a_reqs.csv"
else:
reqsfile = os.getcwd() + "/resources/a_reqs.csv"
This solution will set the reqsfile to the csv in the RequiredFiles directory if the directory exists, and thus will work for you. On the other-hand, if the RequiredFiles directory doesn't exist, it will default to the csv in /resources/.
Typically when groups collaborate on projects, the maintain the same file hierarchy so that these types of issues are avoided, so you might want to consider moving the csv from /RequiredFiles/ to /resources/.

How to open a specific path with open()?

I'm trying to build a file transfer system with python3 sockets. I have the connection and sending down but my issue right now is that the file being sent has to be in the same directory as the program, and when you receive the file, it just puts the file into the same directory as the program. How can I get a user to input the location of the file to be sent and select the location of the file to be sent to?
I assume you're opening files with:
open("filename","r")
If you do not provide an absolute path, the open function will always default to a relative path. So, if I wanted to open a file such as /mnt/storage/dnd/5th_edition.txt, I would have to use:
open("/mnt/storage/dnd/4p5_edition","r")
And if I wanted to copy this file to /mnt/storage/trash/ I would have to use the absolute path as well:
open("/mnt/storage/trash/4p5_edition","w")
If instead, I decided to use this:
open("mnt/storage/trash/4p5_edition","w")
Then I would get an IOError if there wasn't a directory named mnt with the directories storage/trash in my present folder. If those folders did exist in my present folder, then it would end up in /whatever/the/path/is/to/my/current/directory/mnt/storage/trash/4p5_edition, rather than /mnt/storage/trash/4p5_edition.
since you said that the file will be placed in the same path where the program is, the following code might work
import os
filename = "name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
Its pretty simple just get the path from user
subpath = raw_input("File path = ")
print subpath
file=open(subpath+str(file_name),'w+')
file.write(content)
file.close()
I think thats all you need let me know if you need something else.
like you say, the file should be in the same folder of the project so you have to replace it, or to define a function that return the right file path into your open() function, It's a way that you can use to reduce the time of searching a solution to your problem brother.
It should be something like :
import os
filename = "the_full_path_of_the_fil/name.txt"
f = open(os.path.join(os.path.dirname(__file__),filename))
then you can use the value of the f variable as a path to the directory of where the file is in.

Categories