I'm trying to read a .json file from within my Flask application using:
def renderblog():
with open(url_for("static", filename="blogs.json")) as blog_file:
data = json.load(blog_file)
However I get the error:
FileNotFoundError: [Errno 2] No such file or directory: '/static/blogs.json'
Now I know for a fact that the directory exists within my project structure, but I have no idea why I'm getting this error. Any ideas? Is there a specific way to retrieve .json in Flask?
You generated a URL path, not a path to the local static folder. Use the app.static_folder attribute instead:
def renderblog():
filename = os.path.join(app.static_folder, 'blogs.json')
with open(filename) as blog_file:
data = json.load(blog_file)
Related
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'm following a simple tutorial on YouTube about how to automatically upload files in S3 using Python, and I'm getting this error shows that:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'age.csv'
And this does not make sense to me, because files are there. For example, this my code looks like:
client = boto3.client('s3',
aws_access_key_id=access_key,
aws_secret_access_key=secret_access_key)
path = 'C:/Users/User/Desktop/python/projects/AWS-Data-Processing/example_data'
for file in os.listdir(path):
upload_file_bucket = 'my-uploaded-data'
print(file)
if '.txt' in file:
upload_file_key_txt = 'txt/' + str(file)
client.upload_file(file, upload_file_bucket, upload_file_key_txt)
print("txt")
elif '.csv' in file:
upload_file_key_csv = 'csv/' + str(file)
client.upload_file(file, upload_file_bucket, upload_file_key_csv)
print("csv")
And when I comment out the part where it says:
client.upload_file(file, upload_file_bucket, upload_file_key_txt)
it prints out either "txt" or "cvs", and I comment out to just read files such as:
for file in os.listdir(path):
upload_file_bucket = 'my-uploaded-data'
print(file)
Then it successfully prints out the file names. So I don't understand why I get the error of there is no file existing when there is. It sounds contradicting and I need some help to understand this error.
I read a post where I might need to download AWS CLI, so which I did but it didn't help. I'm guessing the problem lies in the function upload_file but I just don't understand how there is no file?
Any advice will be appreciated!
The upload_file function takes a full file path, and not just a name. It cannot guess what is your directory, so you need to prepend it or use a different way of iterating over the files.
Source: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html
I have a list of filenames and I wish to find the checksum of the each file and store in a list displaying [filename,checksum].
New to programming so I tried creating a for loop taking the files from directory. I then used hashlib.md5 to open file with its path and print the filename alongside the checksum.
directory = os.listdir(path)
def file_as_bytes(file):
with file:
return file.read()
for fx in directory:
pass
print[(fx, hashlib.md5(file_as_bytes(open(fx, 'rb'))).digest())]
This is the error I obtain:
IOError: [Errno 2] No such file or directory: 'c.txt'
Which I never created in my client.
I only wish to display the checksum of each file that I have in my client (that already exist)
Instead of :
open(fx, 'rb')
use:
open(os.path.join( path, fx), 'rb')
This question already has answers here:
Refering to a directory in a Flask app doesn't work unless the path is absolute
(1 answer)
Saving upload in Flask only saves to project root
(1 answer)
Get root path of Flask application
(2 answers)
Closed 4 years ago.
There are 2 functions or views located in the same file version.py, one for upload the other for downloading that file. The issue is that the send_file function keeps changing directories while opening the file.
Code 1:
File Upload function:
binfile = form.binfile.data
filename = secure_filename("arduino.bin")
#without the app folder
binfile.save(os.path.join(
app.config['UPLOAD_FOLDER'],
device_names.farm_id,
device_names.mqtt_id,
filename))
flash('File Uploaded', 'success')
File Download Function:
file_path = os.path.join(
app.config['UPLOAD_FOLDER'],
farm_id,
device_id,
'arduino.bin')
print(file_path)
response = make_response(send_file(
file_path,
mimetype='application/octet-stream',
as_attachment=True
))
response.headers['x-MD5'] = md5(file_path)
print(response.headers)
return response, 200
Here the file gets uploaded to the project root folder.
When I send a request for this file, I get this error:
[Errno 2] No such file or directory:
‘/home/maxwell/Desktop/python/aquaponics-monitor/app/firmware-manager/FARM0/node2/arduino.bin’
When I manually move the file to the 'app' folder I get no errors and a 200 response code while requesting. So I assume that the function is looking for the file inside the 'app' folder. I changed the upload location by adding 'app' to the path while uploading.
Code 2:
File Upload Function:
binfile = form.binfile.data
filename = secure_filename("arduino.bin")
#app folder included
binfile.save(os.path.join(
'app',
app.config['UPLOAD_FOLDER'],
device_names.farm_id,
device_names.mqtt_id,
filename))
flash('File Uploaded', 'success')
The file download function is the same as code 1. For this code I get this error:
[Errno 2] No such file or directory:
‘firmware-manager/FARM0/node2/arduino.bin’
The file download function now looks in the project root folder. I manually moved the file to the root folder this time and I again get a status code 200 and no errors when I send a request for it.
The only code change I made in the entire application is adding 'app' to the path in the File Upload function. Why is this happening?
Im creating a new thread to ask this question because i have tried every solution i found but non seems to be working for me. I want to output pdf files stored in media sub directory. #Compadre suggested some links that really helped me understand how the file system works in python but so solutions provided in the threads are not working. i want to output files in the following directory structure:
media/QuestionPapers/filename.pdf
view function for outputting the file is:
def Display(request, file_name):
File_Name = file_name.replace('_', ' ')
file_path = os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name)
with open(file_path,'rb') as pdf:
response = HttpResponse(pdf.read(), content_type = 'application/pdf')
response['Content-Disposition'] = 'attachment; filename=some_file.pdf'
return response
when i do
return HttpResponse(os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name))
it returns the absolute path to the file i like to out put but i when use the path in my code as shown above i get the is Errors:
[Errno 2] No such file or directory: 'C:\\Users\\majmaj\\projects\\qbank\\Scripts\\QuestionBank\\media\\QuestionPapers\\filename.pdf'
the directory and file does exist because when i do http://127.0.0.1:8000/media/QuestionPapers/myfile.pdf, the file is opened but i don't know why the open() is not working even when the path to the file is correctly
so one should please look into this and tell me what I'm doing wrong, I'm stuck with this issue and its driving me nuts. this is the fifth day and still no solution