I would like to use images with tkinter's canvas but I can't open image with Pillow. In fact, I have all my images in the same folder as my code but when I put "icon.png" it doesn't work. Then when I put the full path to the image (C:/Users/myName/Desktop/PythonWork/game/src/icon.png) , it works.
File "F:\Python\lib\site-packages\PIL\Image.py", line 2312, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'icon.png'
Therefore my question is : How do I make the relative path to work ?
Thanks in advance for your help :)
If you want to reference files in the same directory as in Image.py, put this in Image.py:
import os
# get the directory path of the current python file
my_path = os.path.dirname(__file__)
You can then append to that path the name of the file you want to access.
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..
This is a school program to learn how to use file and directory in Python. So to do my best I create a function to open, set it as a variable and close properly my file.
But I got the error of the title:
FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'
def load_db():
""" load data base properly
And get ready for later use
Return:
-------
cd : (list) list of tuples
"""
file = open('codedata.pkl', 'rb')
codedata = pickle.loads(file)
file.close()
return codedata
From the interpreter, this is the line
file = open('codedata.pkl', 'rb')
Which is the problem, but I don't see where is the source of the problem.
Can anyone help me?
Can you check what is the location of the file?
If your file is located at /Users/abc/Desktop/, then the code to open the file on python would be as shown below
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
You can also check if the file exists at the desired path by doing something like this
import os
filepath = '/Users/abc/Desktop/codedata.pkl'
if os.path.exists(filepath):
file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()
else:
print("File not present at desired location")
it happens when you run the script without determining it's the current working directory (example in vs code if you go to Explorer Tape )
You do not work from the same directory that your data.pkl in that's why No file exists
You can know the current directory from getcwd() usually it will be the C/User/.
print(os.getcwd())
filepath=""
if os.path.exists(r"D:\research\StleGAN\karras2019stylegan-ffhq-1024x1024.pkl"):
print("yes")
else:
print("no")
The solution is to open a directory that contains the script or to add the full path.
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()
I'm trying to get an image to show on the screen. I have the image file and code file in the same folder. I tried using the image file name and it said that there is no such file or directory. How do I do that?
I think you should try to write absolute path. you can use following code
import os
path = os.getcwd()
abs_path = path + img_name
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())