I am working on a dictionary project. So, I downloaded a JSON file and placed it on my desktop. I tried to import it into my Python file but it says the file is not found.
FileNotFoundError: [Errno 2] No such file or directory: 'data.json'
Here's my code:
import json
data = json.loads(open('data.json'))
print(data)
You can use os.path.expanduser to get the home directory of the current user and then using os.path.join you can obtain the full path to data.json located in Desktop directory.
Use:
import os
import json
filepath = os.path.join(os.path.expanduser("~"), "Desktop", "data.json")
with open(filepath) as file:
data = json.load(file)
print(data)
Related
Hello as the title says i am writing a program which copys data from chrome. my current code is
#library imports
import sys
import shutil
import os
import subprocess
#search and find requried files.
os.path.expanduser('~user') #search for user path
#Making directory
newpath = r'F:\Evidence\Chromium'
newpath = r'F:\Evidence\Chrome'
#Copy chrome file
original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
target = r'F:\Evidence\Chrome'
shutil.copyfile(original, target)
i get a error on the line original = r'%LOCALAPPDATA%\Google\Chrome\User Data\Default\History'
i assume the script cannot read %LOCALAPPDATA%\ and needs the correct user path ?
what code do i need to input the user directory on a windows PC?
for example C:\Users\(Script to find out this part)\AppData\Local\Google\Chrome\User Data\Default
Scripv3.py", line 25, in <module>
shutil.copyfile(original, target)
File "C:\Users\darks\AppData\Local\Programs\Python\Python39\lib\shutil.py", line 261, in copyfile
with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
FileNotFoundError: [Errno 2] No such file or directory: '%LOCALAPPDATA%\\Google\\Chrome\\User Data\\Default\\History'
Use the pathlib library.
from pathlib import Path
original = Path.home() / "Google/Chrome/User data/Default/History"
target = Path("F:/Evidence/Chrome")
shutil.copyfile(origina, target)
What you want to do is use os.path.expandvars() function on original variable:
os.path.expandvars(r'%LOCALAPPDATA%')
Will return:
C:\Users\USERNAME\AppData\Local
Where USERNAME is the name of the current user.
So, ensure the variables are expanded for this path:
original = os.path.expandvars(original)
before using it in shutil.copy(original, target)
I am working on a small python project and found myself having to read a json file. I tried with this little script found on the web, but it gives me a 404 error.
I have a folder containing the json file (datasets.json) and the python file which, for some reason, does not find the json one.
with open('datasets.json', 'r') as file:
dataset = json.loads(file.read())
print(dataset)
Traceback (most recent call last): File "Desktop/proj/ai/index.py", line 4, in with open('datasets.json', 'r') as file: FileNotFoundError: [Errno 2] No such file or directory: 'datasets.json'
The problem is that a relative path depends of the current directory, when you compile a python file the current directory isn't the file's one. Try using an absolute path. You can also transform a relative path to absolute by using os module.
import os
relativePath = './hello/world.py'
absolutePath = os.path.abspath(relativePath)
print(absolutePath)
I'm struggling with reading a file in python, the py file and CSV file are in the same folder but the VSCode makes an error and can't find the file:
import csv
with open('file.csv','r') as f:
reader = reader(f)
...
how can I fix this??
and the error is:
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'file.csv'
If you run:
import os
os.getcwd()
You'll find out your current working directory which I assume is not the one you were expecting. If you're running the python script through VS code it could be using it could be the directory which you have open on the left hand side.
So either run the python using the correct working directory or use an absolute path like this:
import csv
with open('pathname/file.csv','r') as f:
reader = reader(f)
There might be an issue with your relative path settings.
Try this:
import os
import csv
dir = os.path.dirname(__file__)
filename = os.path.join(dir, 'file.csv')
with open(filename,'r') as f:
reader = reader(f)
Are you using spyder?
If so, please check if the current working path is the path your py file locates.
import csv
with open('file.csv','r') as f:
reader = csv.reader(f)
in this case your file.csv should be in folder where is your python script (current working folder)
or, instead of 'file.csv' you can put absolute path
I have a folder that stores a json file in my django application folder, ie, test_data/data.json.
In my tests.py, I am trying to read this file using the following code:
with open('/test_data/data.json', 'r') as f:
self.response_data = json.load(f)
However, I keep on getting the following error:
FileNotFoundError: [Errno 2] No such file or directory: '/test_data/data.json'
What am I doing wrong? Thanks.
Edit: I tried removing the leading slash, yet I still get the same error.
import os
try this
with open(os.getcwd() + '/test_data/data.json', 'r') as f:
self.response_data = json.load(f)
If you're opening files in directories close to where your code is, it is common to place
import os
DIRNAME = os.path.dirname(__file__) # the directory of this file
at the top of the file.
Then you can open files in a test_data subdirectory with
with open(os.path.join(DIRNAME, 'test_data', 'data.json'), 'rb') as fp:
self.response_data = json.load(fp)
you probably want to open json files, which should be utf-8 encoded, in 'rb' (read-binary) mode.
I am newer to python. I was try open the pdf files and write its content into the
new text files. That the text files name are generate by the pdf name. I tried so far but it is not give what i expect. How can i achieve it
import glob, os
import pyPdf
os.chdir("pdf/")
for file in glob.glob("*.pdf"):
filena = file
filename = "c:/documents/"+filena+".txt"
target = open(filename,'w')
pdf = pyPdf.PdfFileReader(open(filena,"rb"))
for page in pdf.pages:
target.write (page.extractText())
target.close()
Results the Error
File "c:/documents/atpkinase.pdf.txt",line 7, in <module>
target = open(filename,'w')
IOError: [Errno 2] No such file or directory: "c:/documents/atpkinase.pdf.txt"
Looks like if the directory "c:/documents/" does not exist. To write file to it you must create directory first. To check directory existent (and create it if needed) you can use
dir = "c:/documents"
if not os.path.exists(dir):
os.makedirs(dir)
Also, filea contains file name with extension, and when you create filename you need only a file name of old file without extension.