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.
Related
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
Opened VS code thru Anaconda3 and when trying to read a csv using pandas
df = pd.read_csv('file.csv')
My file.csv exists in same directory as my panda.py file but i receive a
FileNotFoundError: [Errno 2] File b'file.csv' does not exist: b'file.csv'
I can physically see the file in the same directory but my terminal says its not.
Why is this happening and how can i fix it?
${cwd} - the task runner's current working directory on startup.
The default setting of 'cwd' is the "${workspaceFolder}". In VSCode, the relative path depends on the setting parameter 'cwd', unless you use an absolute path. It doesn't care the relative path to your python file, it just cares the relative path to 'cwd'.
So you have two solutions to solve this problem:
First One:
Use the absolute path as you had tried and worked:
df = pd.read_csv(r'C:\Users\First Last\Documents\StatPython\file.csv')
or
df = pd.read_csv('C:\Users\irst Last\Documents\StatPython\file.csv')
Second One:
Take the path relative to default ${cwd}:
df = pd.read_csv('[the path of cwd][some paths]\file.csv')
In this case, seems like you haven't created a project of 'StatPython'. If it is your project name and opened by VSCode your code should be worked.
this is because you are using a DataFrame to read the csv file while the DataFrame module cannot do that.
Instead you can try using pandas to do the same operation by importing it using import pandas as pd and to read the file use pd.read_csv('filename.csv')
Still not sure why my code in question did not work, but this ended up working.
df = pd.read_csv(r'C:\Users\First Last\Documents\StatPython\file.csv')
Not only did i need the full path but an "r" before it.
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())
This question already has answers here:
How do I check whether a file exists without exceptions?
(40 answers)
Closed 6 years ago.
How can I code a Python script that accepts a file as an argument and prints its full path?
E.g.
~/.bin/python$ ls
./ ../ fileFinder.py test.md
~/.bin/python$ py fileFinder.py test.md
/Users/theonlygusti/.bin/python/test.md
~/.bin/python$ py fileFinder.py /Users/theonlygusti/Documents/Online/theonlygusti.github.io/index.html
/Users/theonlygusti/Documents/Online/theonlygusti.github.io/index.html
So, it should find the absolute path of relative files, test.md, and also absolute path of files given via an absolute path /Users/theonlygusti/Downloads/example.txt.
How can I make a script like above?
Ok, I found an answer:
import os
import sys
relative_path = sys.argv[1]
if os.path.exists(relative_path):
print(os.path.abspath(relative_path))
else:
print("Cannot find " + relative_path)
exit(1)
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')
This question already has answers here:
Python raising FileNotFoundError for file name returned by os.listdir
(3 answers)
Closed 4 years ago.
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
if files.endswith(".torrent"):
print(files + time.ctime(os.path.getatime(files)))
I am getting a file not found error when running this script.
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'TORRENT NAME.torrent'
everything works fine until time.ctime(os.path.getatime(files)
is added into the mix.
I would like the script to display 'torrent name' 'date last modified'
for each file in the folder.
Why is the error referencing a file, by name that it says it is unable to find and how can i fix this?
Your files variable is the file name only, not the complete path. Hence it will be looking for it in your current working directory, not where listdir found it.
The following code will use the full path name:
import os
import time
folder = r'C:\users\chris\desktop\torrent'
files = os.listdir(folder)
for file in files:
if file.endswith(".torrent"):
print(file + " " + time.ctime(os.path.getatime(os.path.join(folder,file))))
The os.path.join() combines folder and file to give you a full path specification. For example, os.path.join("/temp","junk.txt") would give you /temp/junk.txt (under UNIX).
Then it uses that in exactly the same way you tried to use just the file variable, getting the last access time and formatting it in a readable manner.
It require absolute path.
os.path.getatime(path)
Return the time of last access of path.
so, open('xxx.torrent') will not work.
Instead, use open('C:\users\chris\desktop\torrents\xxx.torrent')
import os
import time
torrent_folder = os.listdir(r'C:\users\chris\desktop\torrents')
for files in torrent_folder:
if files.endswith(".torrent"):
filepath = os.path.join('C:\users\chris\desktop\torrents',files)
print(files + time.ctime(os.path.getatime(filepath)))