I am new to Mac OS X (10.10.4). I want to write a code by using python 2.7, which first I have to check if a folder "Pictures" exists, and follow by saving a file into it. However, I dunno the folder path.
folder = "~/usr/my_name/Pictures"
However, after I run
path.exists(folder)
The result is false.
What should is the path I should set to folder?
The ~ character signifying the home directory is a shell convention, and doesn't just work outright in Python.
Use the os.path.expanduser() function to have it interpreted like the shell would:
import os.path
folder = os.path.expanduser("~/usr/my_name/Pictures")
Related
just want to ask if this code in python is valid to use on any OS, i mean, i want to use the path then for exporting txt file to desktop so for example if user on Mac will not have problem, or is there another way to do it?
def get_path():
PATH = os.path.normpath(os.path.expanduser('~/Desktop'))
return PATH
On windows you can easily get Desktop path by joining with the environment variable of user. Here is an example:
import os
desktop_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
This should work for most users, Windows as well as Linux and MacOS have their desktop (typically) located under ~/Desktop. Do note however this location can be changed by the user so there is no guarantuee.
Windows: Usually ~/Desktop but can be changed, see https://superuser.com/q/1663587/138216
Linux: Typically ~/Desktop but could be something else, see https://unix.stackexchange.com/questions/391915/where-is-the-path-to-the-current-users-desktop-directory-stored
Mac: Also typcially ~/Desktop http://etutorials.org/Mac+OS/mac+os+x+power+tools/Part+II+Files+Finders+Docks+and+Apps+Including+Classic/Chapter+5+Finagle+Files+and+Foil+Finder+Frustration/The+Desktop+and+the+Desktop+Folder/#:~:text=In%20Mac%20OS%20X%2C%20because,these%20folders%20in%20Chapter%201).
Set-up
I run a script on my computer, located in the directory Users/path/to/my/script.py.
In the script, I use the path to the script, e.g.,
sub_path = 'Users/path/to/my/'
os.chdir(sub_path + 'other_script/')
As you can see, I define sub_path in the code 'manually'.
Problem
I don't want to define the sub_path manually, I'd rather have Python do it for me.
I'm looking for something similar to the code I use to obtain the current working directory: os.getcwd(), but then a code to obtain the directory of the current file.
I mainly find answers similar to this one, which says,
os.path.abspath(os.path.dirname(__file__))
but in the Spyder & Anaconda set-up, this generates a NameError: name '__file__' is not defined.
What can I do?
You if you want to move back one folder/directory you use the .. in your file path.
os.chdir('../other_scripts/')
will work. You may fine it helpful to view this or the wiki.
If you want to move from where you currently are you can use './new_dir/'. If you want to automate how to find other files you may want to read here which says to use os.walk. This may be the same question.
Mark8888 pointed out to run the whole script (run file (F5)) instead of just pieces of the script
this way multiple approaches should work to get the script file location and change the current working directory
import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())
also
import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())
I add the following lines to any script I run in case I need to access data relative to the location of the script
import sys
script = sys.argv[0]
print(script)
'C:/SomeFolder/A_Subfolder/CurrentlyRunningScript.py' # changed obviously
First, save your Jupyter Notebook. Second, locate the directory your Jupyter Notebook is stored in. Thirdly, ensure that your Jupyter Notebook and CSV file are in the same place.
I'm using Windows 10 with VS2015 and Python 3.4. I have created a module called this.py. Now I want to import this.py. That works OK if this.py is in the current folder. But I need this.py to be in a different folder which is used by all of my scripts.
I have tried a few approaches but none would find this.py. One approach was to set my Windows CMD PATH.
Can someone tell me how to set the search path for imports?
You should do something like this:
import sys
sys.path.append("path-here")
Then that directory will be searched when you import something (other than standard directories)
Edit: the path of the directory containing the imported file, not of the file
I'm using Python 2.7.2. and I want to open and use a dictionary I created in my shell. My problem is, when I try to import this dictionary into my shell it can't find the file because python is just looking into the 'my documents' folder.
My question is, how can I navigate to the correct folder (just one folder further in 'my documents' folder.
I am using a Macintosh.
You can add custom path to your script as:
import sys
sys.path.append('/Users/username/')
Another way is to set the PYTHONPATH environment variable to /User/username in your shell. Since you know about your shell, I expect that you already know how to edit your shell resource script. You could also add it to your .profile file in which case it should be available even if you change which shell you happen to be using.
If you don't want to "hardwire" the system path, but want to use a relative folder, you could get the name of the working directory and add your subdirectory to that...
subdirname = 'myfolder'
curdir = os.getcwd()
newdir = os.path.join(curdir,subdirname)
sys.path.append(newdir)
I am working with a Macbook programming python. What I want to know is how I can access certain files using Python's file functions. A google search failed me.
For example, Windows would be something like this:
f = open(r'C:\text\somefile.txt')
How would I access something from a folder saved on the Desktop of a Mac?
The desktop is just a subdirectory of the user’s home directory. Because the latter is not fixed, use something like os.path.expanduser to keep the code generic. For example, to read a file called somefile.txt that resides on the desktop, use
import os
f = open(os.path.expanduser("~/Desktop/somefile.txt"))
If you want this to be portable across operating systems, you have to find out where the desktop directory is located on each system separately.
f = open (r"/Users/USERNAME/Desktop/somedir/somefile.txt")
or even better
import os
f = open (os.path.expanduser("~/Desktop/somedir/somefile.txt"))
Because on bash (the default shell on Mac Os X) ~/ represents the user's home directory.
You're working on a Mac so paths like "a/b/c.text" are fine, but if you use Windows in the future, you'll have to change all the '/' to '\'. If you want to be more portable and platform-agnostic from the beginning, you better use the os.path.join operator:
import os
desktop = os.path.join(os.path.expanduser("~"), "Desktop")
filePath = os.path.join(desktop, "somefile.txt")
f = open(filePath)
If this is still an issue, I had the same problem and called Apple. I learned that the file I'd created was saved on iCloud. The Apple guy told me to save the file locally. I did that and the problem was solved.