List directories python OSX [duplicate] - python

This question already has answers here:
os.makedirs doesn't understand "~" in my path
(3 answers)
Closed 7 years ago.
I am having an issue with trying to list all of the files/folders within a directory with Python 2.6, on Mac OS X.
To simplify the problem, I am attempting to simply list all the files on my desktop (which is not empty). I understand this can be done like this:
currentFileList = os.listdir("~/Desktop")
But I am getting the error:
currentFileList = os.listdir("~/Desktop")
OSError: [Errno 2] No such file or directory: '~/Desktop'
Any suggestions?

You should pass absolute pass to os.listdir function. You can use os.expanduser function to expand ~:
os.listdir(os.path.expanduser('~/Desktop'))
By the way. Be careful: ~foobar will replace the path with home folder for user foobar (e.g. /home/foobar)

You need the full path not relative
os.listdir('/Users/YOURUSERNAME/Desktop')

Related

Trying to save a file fails with (FileNotFoundError: [Errno 2] No such file or directory) for no clear reason [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 6 months ago.
It seems that saving files with long names leads to problems for some reason. I won't write code here since it is hard to reproduce, but below is an image that shows this issue.
Folder structure definitely exists, you can see that for some filenames it works just fine. But then for other names without any weird special characters it fails.
I have tried other variants like giving absolute path, but still it seems to fail. Is there maybe a fix to this, other than saving a file with a timestamp perhaps or some other kind of unique random naming?
EDITFor more clarification, folder structure is the same for each of the 5 examples (everything up to the last \), I have only changed filename and for 3 examples it works fine but for other 2 it doesn't.
You are using path as DATA\\... but path should be either .\\DATA: which means path from current directory or, specify your Drive Name in starting like: C:\\...\\DATA...

Possibility of adding a directory in Python-nested? [duplicate]

This question already has answers here:
How can I safely create a directory (possibly including intermediate directories)?
(28 answers)
Closed 1 year ago.
What is the best way to check if the directory a file is going to be written to exists, and if not, how to create the directory using Python?
Does a flag exists as "open", that makes this happen automatically?
Use makedirs from os module:
os.makedirs(DIRECTORY, exist_ok=True)
This will create a directory if it doesn't exist.

Is there a way to view the directory that a file is in using python? [duplicate]

This question already has answers here:
Find the current directory and file's directory [duplicate]
(13 answers)
Closed 3 years ago.
For a project I am working on in python, I need to be able to view what directory a file is in. Essentially it is a find function, however I have no idea how to do this using python.
I have tried searching on google, but only found how to view files inside a directory. I want to view directory using a file name.
To summarise: I don't know the directory, and want to find it using the file inside it.
Thanks.
In Python, the common standard libraries for working with your local files are:
os.path
os
pathlib
If you have a path to a file & want it's directory, then we need to extract it:
>>> import os
>>> filepath = '/Users/guest/Desktop/blogpost.md'
>>> os.path.dirname(filepath) # Returns a string of the directory name
'/Users/guest/Desktop'
If you want the directory of your script, the keyword you need to search for is the "current working directory":
>>> import os
>>> os.getcwd() # returns a string of the current working directory
'/Users/guest/Desktop'
Also check out this SO post for more common operations you'll likely need.
Here's what I did:
import os
print(os.getcwd())

function that browses every folder in a folder [duplicate]

This question already has answers here:
How to list only top level directories in Python?
(21 answers)
Closed 2 years ago.
How can I bring python to only output directories via os.listdir, while specifying which directory to list via raw_input?
What I have:
file_to_search = raw_input("which file to search?\n>")
dirlist=[]
for filename in os.listdir(file_to_search):
if os.path.isdir(filename) == True:
dirlist.append(filename)
print dirlist
Now this actually works if I input (via raw_input) the current working directory. However, if I put in anything else, the list returns empty. I tried to divide and conquer this problem but individually every code piece works as intended.
that's expected, since os.listdir only returns the names of the files/dirs, so objects are not found, unless you're running it in the current directory.
You have to join to scanned directory to compute the full path for it to work:
for filename in os.listdir(file_to_search):
if os.path.isdir(os.path.join(file_to_search,filename)):
dirlist.append(filename)
note the list comprehension version:
dirlist = [filename for filename in os.listdir(file_to_search) if os.path.isdir(os.path.join(file_to_search,filename))]

An existing file not being identified using os.path.isfile function [duplicate]

This question already has answers here:
os.makedirs doesn't understand "~" in my path
(3 answers)
Closed 6 months ago.
I have a file 7.csv in directory: '~/Documents/Jane/analyst/test/1/'. I was able to read this file using pandas.read_csv function with no problem.
f_path = '~/Documents/Jane/analyst/test/1/7.csv'
pd.read_csv(f_path, index_col=None, header=0)
But when checking whether this file is exsiting using os.path.isfile(), the result return False.
os.path.isfile(f_path)
False
What could be the the possible error source?
Both os.path.isfile() and os.path.exists() do not recognize ~ as the home directory. ~ is a shell variable not recognized in python. It has to be either fully specified or you can use relative directory name.
But if you want to use ~ as home, you can do
from os.path import expanduser
home = expanduser("~")
As hun mentioned, your code should be
import os
f_path = '~/Documents/Jane/analyst/test/1/7.csv'
os.path.isfile(os.path.expanduser(f_path))
This will expand the tilde into an absolute path. ~, . and .. do not have the same meaning to the python os package that they do in a unix shell and need to be interpreted by separate functions.

Categories

Resources