I am trying to use the listdir function from the os module in python to recover a list of filenames from a particular folder.
here's the code:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
list_of_files = os.listdir("/home/admin-pc/Downloads/prank/prank")
print (list_of_files)
I am getting the following error:
OSError: [Errno 2] No such file or directory:
it seems to give no trouble in windows, where you start your directory structure from the c drive.
how do i modify the code to work in linux?
The code is correct. There should be some error with the path you provided.
You could open a terminal and enter into the folder first. In the terminal, just key in pwd, then you could get the correct path.
Hope that works.
You could modify your function to exclude that error with check of existence of file/directory:
import os
def rename_file():
# extract filenames from a folder
#for each filename, rename filename
path_to_file = "/home/admin-pc/Downloads/prank/prank"
if os.exists(path_to_file):
list_of_files = os.listdir(path_to_file)
print (list_of_files)
Related
I have faced error I had worked with this code before but now:
error
FileNotFoundError: [Errno 2] No such file or directory: 'pattern2_list.txt'
I use Python 3.8
import os
import shutil
with open ("pattern2_list.txt") as pattern_list_file:
pattern_data = pattern_list_file.read ()
pattern_list = pattern_data.split('\n')[:-1]
file_name_list = [file_name for file_name in os.listdir('2020')]
for file_name in file_name_list:
for pattern in pattern_list:
if pattern in file_name:
shutil.move("2020/" + file_name, "new_dir/"+ file_name)
Make sure that the file pattern2_list.txt
is present in the same working directory.
If you are in same directory and still it is not working then open a new folder and inside it create your python file with.pyextension.Inside same folder paste the pattern2_list.txtfile and then try to use it.
If still facing issue then check your python path in environment variable and if possible restart your system then open vs code.
Hope it will help you..
I am getting stuck when trying to iterate through files in a directory ('PDFS') with fitz from PyMuPDF.
The thing is, the code works when I am just doing document = "somepdf.pdf", but as soon as I insert a for loop and try to access files that way this error shows up:
filename, stream, filetype, rect, width, height, fontsize
RuntimeError: cannot open sample.pdf: No such file or directory
Here is the code:
for file in os.listdir('PDFS'):
if fnmatch.fnmatch(file, '*.pdf'):
document = file
doc = fitz.open(document)
Thank you for the help!
Your pdf files to open is under sub-directory PDFS, e.g. PDFS/sample.pdf, while your code fitz.open(document) is to open file under current working directory. So, a fix should be:
import fitz
import os
import fnmatch
for file in os.listdir('PDFS'):
if fnmatch.fnmatch(file, '*.pdf'):
document = os.path.join('PDFS', file)
doc = fitz.open(document)
Furthermore, a relative path PDFS is used, so you have to run the code right under the path where PDFS in, say /your/workspace/:
/your/workspace > python code.py
Otherwise,
/your > python workspace/code.py
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'PDFS'
So, a good practice is to
use full path if PDFS is just a user input path; otherwise,
use relative path to the script path
script_path = os.path.abspath(__file__)
project_path = os.path.dirname(script_path)
pdfs_path = os.path.join(project_path, 'PDFS')
I had the same issue. Its because PyCharm automatically installs the module named fitz whereas you need to write the following in the terminal:
pip install PyMuPDF
This will automatically install fitz and you can use the function fitz.open()
Im trying to run my code with this but keep running into a file not found error.
files = [i for i in os.listdir('C:/Users/me/Desktop/python data')]
for filename in files:
data = pandas.read_excel(str(filename))
I've tried looking around but cant seem to understand.
Running print(os.getcwd()) does find the file in the folder but i still get the error message
You need to concatenate the path and the filename returned from os.listdir:
PATH = 'C:/Users/me/Desktop/python data'
files = [os.path.join(PATH, i) for i in os.listdir(PATH)]
for filename in files:
data = pandas.read_excel(str(filename))
Further recommendations:
You can use pathlib's .glob to get the full path without using os.path.join.
Also, if you use read_excel, please consider filtering by xls/xlsx files:
Code example:
import pathlib
path = pathlib.Path('C:/Users/me/Desktop/python data')
excel_filter = "*.xls*"
for filename in path.glob(excel_filter):
print(filename)
I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.
In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:
current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)
/Users/johnsmith/Documents/pythonprojects/project/files/john
Now I want to obtain the path for the existing file I want to rename:
current_file_path = os.path.join(current_user_path,form.currentTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/File1
The path for the rename file will be:
new_file_path = os.path.join(current_user_path, form.newTitle.data)
/Users/johnsmith/Documents/pythonprojects/project/files/john/One
Now I'm just running the rename command:
os.rename(current_file_path, new_file_path)
you can use os.rename for rename single file.
to avoid
OSError: [Errno 2] No such file or directory.
check if file exist or not.
here is the working example:
import os
src = "D:/test/Untitled003.wav"
dst = "D:/test/Audio001.wav"
if os.path.isfile(src):
os.rename(src, dst)
If the OS says there's no such file or directory, that's the gospel truth. You're making a lot of assumptions about where the file is, constructing a path to it, and renaming it. It's a safe bet there's no such file as the one named by current_file_path, or no directory to new_file_path.
Try os.stat(current_file_path), and similarly double-check the new file path with os.stat(os.posixpath.dirname(new_file_path)). Once you've got them right, os.rename will work if you've got permissions.
Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should go about it:
import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
file_list= os.listdir(r"D:\Python\Example")
print(file_list)
for file_name in file_list:
os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())
I am trying to zip and compress all the files in a folder using python. The eventual goal is to make this occur in windows task scheduler.
import os
import zipfile
src = ("C:\Users\Blah\Desktop\Test")
os.chdir=(src)
path = (r"C:\Users\Blah\Desktop\Test")
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
zf.write(file)
Now when I run this script I get the error:
WindowsError: [Error 2] The system cannot find the file specified: 'test1.bak'
I know it's there since it found the name of the file it can't find.
I'm wondering why it is not zipping and why this error is occurring.
There are large .bak files so they could run above 4GB, which is why I'm allowing 64 bit.
Edit: Success thanks everyone for answering my question here is my final code that works, hope this helps my future googlers:
import os
import zipfile
path = (r"C:\Users\vikram.medhekar\Desktop\Launch")
os.chdir(path)
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
zf.write(os.path.join(file))
zf.close()
os.listdir(path) returns names relative to path - you need to use zf.write(os.path.join(path, file)) to tell it the full location of the file.
As I said twice in my comments:
Python is not looking for the file in the folder that it's in, but in the current working directory. Instead of
zf.write(file)
you'll need to
zf.write(path + os.pathsep + file)