Python FileNotFoundError even if the File is there - python-3.x

My project directory tree is something like this,
build
----fonts
--------Roboto Bold.ttf
----main.py
The following code errors out,
from pyglet import font
font.add_file("fonts\\Roboto Bold.ttf")
Also tried this code,
import os
from pyglet import font
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
the error is,
Traceback (most recent call last):
File "{full_dir_name}\build\main.py", line 25, in <module>
font.add_file(str(os.getcwd())+'\\fonts\\Roboto Bold.ttf')
File "C:\python-3.8.5-amd64\lib\site-packages\pyglet\font\__init__.py", line 183, in add_file
font = open(font, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '{full_dir_name}\\fonts\\Roboto Bold.ttf'
I have tried about a day now and also seen other posts here but could not resolve...

The resource (image, font, sound, etc.) file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd(). If the file is in an subfolder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the relative filepath. e.g.:
font.add_file(str(os.getcwd())+"\\fonts\\Roboto Bold.ttf")
font.add_file(os.path.join(os.path.dirname(os.path.abspath(__file__)), "fonts/Roboto Bold.ttf"))

Related

FileNotFoundError: No such file or directory in pygame [duplicate]

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
I am somewhat new to programming, I don't like it that much but as it is school work I have to do it, good thing I find it interesting.
Here is my code, note I'm using VS code (some things are in french but that shouldn't affect anything):
import pygame
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space vaders")
fond = pygame.image.load (testingfield.png)
and I get:
Traceback (most recent call last):
File "c:/Users/faver/Desktop/Space_Invaders-NSI/space_invaders_1.py", line 11, in <module>
fond = pygame.image.load ('testingfield.png')
FileNotFoundError: No such file or directory.
the file is indeed in the folder, and if I put fond = pygame.image.load ((r'C:\Users\faver\Desktop\Space_Invaders-NSI\testingfield.png'))it works perfectly, the problem now is that it'd be hard to actually send it since the other person would lack the folders I place there.
I've also tried import os a = os.path.lexists("/Users/suyeon/Documents/pythonWorkspace/pygame_basic/character.png") print(a) and it returned false, so I'm pretty much confused, I'd appreciate help if possible ^^'
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd() and can be changed by os.chdir(path).
One solution is to change the working directory:
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
An alternative solution is to find the absolute path.
If the image is relative to the folder of the python file (or even in the same folder), then you can get the directory of the file and join (os.path.join()) the image filename. e.g.:
import pygame
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
# join the filepath and the filename
fondImgPath = os.path.join(sourceFileDir, 'testingfield.png')
fond = pygame.image.load(fondImgPath)

pdfkit [WinError 740] The requested operation requires elevation python3

I would like to convert an HTML page into a PDF file, based on the given URL. I have tried pdfkit, but it throws the following error:
[WinError 740] The requested operation requires elevation.
Code:
import pdfkit
path_wkthmltopdf = "D:\\w.exe"
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf )
pdfkit.from_url("http://www.google.com", 'd:\\out.pdf', configuration=config)
Output error:
n [42]: import pdfkit
path_wkthmltopdf = "D:\\w.exe"
config = pdfkit.configuration(wkhtmltopdf = path_wkthmltopdf )
pdfkit.from_url("http://www.google.com", 'd:\\out.pdf', configuration=config)
Traceback (most recent call last):
File "<ipython-input-42-58323936ac63>", line 5, in <module>
pdfkit.from_url("http://www.google.com", 'd:\\out.pdf', configuration=config)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\site-packages\pdfkit\api.py", line 26, in from_url
return r.to_pdf(output_path)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\site-packages\pdfkit\pdfkit.py", line 129, in to_pdf
stderr=subprocess.PIPE)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 143, in __init__
super(SubprocessPopen, self).__init__(*args, **kwargs)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\subprocess.py", line 729, in __init__
restore_signals, start_new_session)
File "C:\Users\31081\AppData\Local\conda\conda\envs\ml\lib\subprocess.py", line 1017, in _execute_child
startupinfo)
OSError: [WinError 740] The requested operation requires elevation
I encountered with this problem too, I solved it by running .exe after run this it will create new dir, go inside this dir then bin dir you will find a exe file there like
C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
So, replace "D:\w.exe" to above kind of path in your code then it will work
Cause
You are most likely getting that error as a result of downloading the Installer version, but not installig it. Thus, when running your code with wkhtmltopdf in the configuration pointing to that executable (which requires elevation of privilege), you get the following error:
OSError: [WinError 740] The requested operation requires elevation
Solution
You could install wkhtmltopdf by running that Installer version and choosing the destination folder (let's say C:\Program Files). You will find the wkhtmltopdf.exe file that you need to add to your configuration inside the bin folder. Hence, you should use as follows:
config = pdfkit.configuration(wkhtmltopdf=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
pdfkit.from_url('http://google.com', 'out.pdf', configuration=config)
Another solution would be to download the 7z Archive version, extract the files, in which you'll find wkhtmltopdf.exe under the bin folder as well.
I ran into this issue when I had not gone through the full installation of the wkpdftohtml library. Once it was unpacked, this ran without need for elevation.

MoviePy Error: The system cannot find the file specified

I'm getting the error in the title when trying to run the example code below on Windows 10/Python 3.6.1/Sublime Text Editor 3. I made sure to set my MAGICK_HOME environment variable to point to where I manually installed ImageMagick. I made sure to only have 1 version of ImageMagick installed. I made sure FFMPEG, Numpy, imageio, Decorator, and tqdm were all installed.
Yes, the file "vidclip.mp4" exists. The desired behavior here is to simply clip the video and add text to the center as per the example on the github page, i.e. to simply run the code successfully.
Does anyone know what might be wrong?
Example code from github:
from moviepy.editor import *
video = VideoFileClip("vidclip.mp4").subclip(7,64)
# Make the text. Many more options are available.
txt_clip = ( TextClip("Ken Block who?",fontsize=70,color='white')
.set_position('center')
.set_duration(10) )
result = CompositeVideoClip([video, txt_clip]) # Overlay text on video
result.write_videofile("vidclip_edited.webm",fps=25) # Many options...
The full error trace:
Traceback (most recent call last):
File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1220, in __init__
subprocess_call(cmd, verbose=False )
File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\tools.py", line 42, in subprocess_call
proc = sp.Popen(cmd, **popen_params)
File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 707, in __init__
restore_signals, start_new_session)
File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\subprocess.py", line 990, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\av\Desktop\Desktop\Projects\Youtube\blender\test\testMoviePy.py", line 6, in <module>
txt_clip = ( TextClip("Ken Block who?",fontsize=70,color='white')
File "C:\Users\av\AppData\Local\Programs\Python\Python36\lib\site-packages\moviepy\video\VideoClip.py", line 1229, in __init__
raise IOError(error)
OSError: MoviePy Error: creation of None failed because of the following error:
[WinError 2] The system cannot find the file specified.
.This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or.that the path you specified is incorrect
Found the problem. I didn't realize it was imperative that I specify the location of ffmpeg.exe and convert.exe within ImageMagick's config_defaults.py file. After that, I install MoviePy (in that order).

Accessing files in directory outside of Anaconda

Newb here to python/anaconda.
I'm trying to run a python script (and it reads other files local to its directory) which doesn't belong to the same directory as the Anaconda directory where I'm executing the python command there.
So I am trying to run a python script (lets say it resides in path B directory) from the Anaconda python (say path A directory). Within this script, there is a call to reading a local file so we have only the fileName.py and then the command prompt spits out this error:
C:\Users\usernameABC\Anaconda3>python C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py
Traceback (most recent call last):
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 165, in <module>
main()
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 130, in main
resp = ReadFemResp()
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\nsfg.py", line 27, in ReadFemResp
dct = thinkstats2.ReadStataDct(dct_file)
File "C:\Users\usernameABC\Documents\GitHub\python\ThinkStats2\code\thinkstats2.py", line 2646, in ReadStataDct
for line in open(dct_file, **options):
FileNotFoundError: [Errno 2] No such file or directory: '2002FemResp.dct'
I basically just want to run the script, whether its in Anaconda or wherever is the easiest or most natural that most experienced coders would. Please help! Thanks in advance for feedback!
You can change your current working directory using the
cd (change directory) command
You can also modify the script so that you can specify where the files are that you want to access. If you show us the script that you are running we may be able to help more.

Cx_Freeze compiled pygame file doesn't work

The following error happens if i try to compile my python (using python 3.2) file:
Traceback(most recent call last):
File
"c:\python32\lib\site-packages\cx_Freeze\initscripts\Console3.py", line
27, in <module>
exec(code, m.__dict__)
File "Abertura.py", line 208, in <module>
File "Abertura.py", line 154, in main
File "Abertura.py", line 9, in __init__
pygame.error: Couldn't open
C:\Python32\build\exe.win32-3.2\library.zip\Imagens\menu1.png
I already included pygame._view and tried to copy the 'Imagens' directory to the library.zip file, but it doesn't work. I'm using images, musics and videos that come's from other directories by including in my code:
def file_path(filename, directory):
return os.path.join(
os.path.dirname(os.path.abspath(__file__)),
directory,
filename
)
And this is my setup.py file:
from cx_Freeze import setup, Executable
exe=Executable(
script="Abertura.py",
base="Win32Gui",
)
includefiles=[('C:\Python32\Imagens', 'Imagens'),
('C:\Python32\Musicas','Musicas'),
('C:\Python32\Videos','Videos')
]
includes=[]
excludes=[]
packages=[]
setup(
version = "1.0",
description = "RPG",
author = "Pedro Forli e Ivan Veronezzi",
name = "Batalha Inapropriada",
options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
executables = [exe]
)
How do i fix it?
(sorry about my possibles english mistakes)
Anything accessed from within a compressed archive (such as zips, rars, tar.gzs, etc...) need to be decompressed first before you access them.
That being said, you should not have your recourse files in a zip because decompressing it every time to want to access something is slow, and difficult. Your resource files should be in a normal directory, not an archive.
The reason why you're getting this error is because it's looking for a folder named library.zip and it's not finding one because library.zip is not a folder, it's a file.
How I would suggest to combat this error is to extract everything into a folder named library and to change in your code anywhere that library.zip exists to library.

Resources