Python raising FileNotFoundError for file name returned by os.listdir
It is because os.listdir
does not return the full path to the file, only the filename part; that is 'foo.txt'
, when open would want 'E:/somedir/foo.txt'
because the file does not exist in the current directory.
Use os.path.join
to prepend the directory to your filename:
path = r'E:/somedir'
for filename in os.listdir(path):
with open(os.path.join(path, filename)) as f:
... # process the file
(Also, you are not closing the file; the with
block will take care of it automatically).
How to avoid a FileNotFoundError with os.listdir
The path to your file is compose from root_path + your file name, you can use :
from pathlib import Path
root_path = Path(root_dir)
for filename in os.listdir(root_path):
if filename.endswith('.csv'):
# Pull in the file
df = pd.read_csv(root_path/filename)
or you can use:
for filepath in root_path.glob("*.csv"):
df = pd.read_csv(filepath)
Getting FileNotFoundError: when I try to read the excel files in my directory
filename
only contains the name of the file and not its entire path. Your script does not see the file since it's looking for it where you are and not in the directory
folder. You need to add the path to the file:
import os
directory = r"C:\Users\andre\OneDrive\Desktop\python_web_scrapper\Cleaned_Data"
for filename in os.listdir(directory):
if filename.endswith(".xlsx"):
pd.read_excel(os.path.join(directory, filename))
listdir() No such file or directory
You try to open 'yo.jpg' in your root directory but you get your filenames from the 'path' directory.
Try to change line 11 to:
i = Image.open(path + f)
Error while using listdir in Python
I decided to change the code into:
def numOfFiles(path):
return len(next(os.walk(path))[2])
and use the following the call the code:
print numOfFiles("client_side")
Many thanks to everyone who told me how to pass the windows directory correctly in Python and to nrao91 in here for providing the function code.
EDIT: Thank you eryksun for correcting my code!
Python says it can't find the file I am trying to rename even though it can read the file name
I thought my comment might be enough, but for clarity I'll provide a short answer.
02.png
doesn't exist relative to your working directory. You need to specify the path to the file for os.rename
so you need to include the directory.
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "/pics/{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",)) # Notice the ./pics
os.rename(os.path.join('pics', file), newFileName)
Python: IOError with os.listdir - files exist but are not found
Try this
import os
directoryPath=raw_input('Directory for csv files: ')
for file in os.listdir(directoryPath):
if file.endswith(".csv"):
filelabel=file[:-4]
strPath = os.path.join(directoryPath, file)
x=numpy.genfromtxt(strPath, delimiter=',')
ans = x[:,2]
Why is os.listdir showing to a file while I set it to the directory?
shutil.rmtree
deletes an entire directory tree.
To remove a single file, you can use os.remove
.
Related Topics
Django - No Such Table: Main.Auth_User_Old
Performing a Getattr() Style Lookup in a Django Template
Python: Maximum Recursion Depth Exceeded
Matplotlib Does Not Show My Drawings Although I Call Pyplot.Show()
Renaming a Virtualenv Folder Without Breaking It
Stream Large Binary Files with Urllib2 to File
Handling Backreferences to Capturing Groups in Re.Sub Replacement Pattern
How to Send an Email with Python
How to Execute a Python Script from the Django Shell
How to Define a Function with Optional Arguments
What Is the Cause of the Bad Request Error When Submitting Form in Flask Application
Subclassing Tuple with Multiple _Init_ Arguments
Test If Executable Exists in Python
Pandas: Peculiar Performance Drop for Inplace Rename After Dropna