I am trying to read in a JSON file called league.json from a python file called run_test.py. The JSON file is in a different directory. I am running Windows 10 and python 3.8.6 in Visual Studio.
The directory I'm running the python file in is: C:\Users\my_un\Documents\folder1\folder2\model\run_test.py
The directory I am trying to load the json file from is:
C:\Users\my_un\Documents\folder1\folder2\config\league.json
Based on documentation I've found, the below code should work, but I keep getting the error: FileNotFoundError: [Errno 2] No such file or directory: 'config\league.json'.
This does run successfully when I move league.json to the same directory as the python file, and change the open location to: '.\league.json'.
What am I doing wrong? My code is below. Thanks in advance.
import json
with open('.\config\league.json', 'r') as f:
config = json.load(f)
print (len(config))
change the path to open('..\config\league.json', 'r') , by adding one more .
if the above doesn't work, use abspath to find the path of league.json and pass in the open(path) function
The folder 'config' needs to be in the folder 'model' for your code to run. Otherwise change your code to
open('C:\Users\my_un\Documents\folder1\folder2\config\league.json', 'r')
Related
I have encountered a problem while trying to open a .txt file from the same directory where my source code is located.
When I tried to open the file like this:
with open("pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
I failed.
I also failed when I typed the whole path:
with open("Users\lukas\Documents\python_work\chapter_10") as file_object:
contents = file_object.read()
print(contents)
But when I typed:
with open("\\Users\\lukas\\Documents\\python_work\\chapter_10\\pi_digits.txt") as file_object:
contents = file_object.read()
print(contents)
I succeeded!
So my question is: Why can't I run the code without error when I enter the following code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
Thank you for your answers and sorry if my question was not well constructed.
#Sottvogel
In general, a python instance can be run from many different directories in your computer. One way to check where the running instance is:
import os
os.getcwd()
If you confirm that you are in the same directory of your file, try and see
what the following returns:
os.listdir()
In case your file doesn't appear in the returned string, then there has to be another problem. Make sure you checkout the docs as well.
Hope it helps!
the thing with paths is python is that they are referenced from where you launch the program (current working directory), not from where the file lives. So, I recommend making use of the os and pathlib packages to manage file paths properly.
Why can't I run the code without error when I enter the following code:
It depends from where you execute your python code.
Building on above, where you execute your code implies wether you need to use the file name or it's path.
If you execute your Python code in the same directory as the txt file, then you can use the file's name. However, if it is located elsewhere the script will need to access the file and hence, requires the path to it.
I've been trying to solve this issue, but right now I need some help. I'm trying to upload this JSON file (DBL) in Spyder IDE. I have stored the JSON-data file and the Spyder file, in the same map in order to read the JSON file, but it's not working.
My Python code:
import json
file = open("dbl")
dbl = json.load(file)
print(dbl)
Every time I upload the json file, in the same map as the spyder.py file, it can't recognize the file directory.
I have stored the my .py file in the same folder as the JSON file.
This is the error message:
FileNotFoundError: [Errno 2] No such file or directory: 'dbl.json'
The file, in fact, does not exist. The actual filename is dbl.json.json.
import json
file = open("dbl.json.json")
dbl = json.load(file)
print(dbl)
You'll use ".json" in the file path.
For example:
file = open("dbl.json")
if dbl is name of json file then you should add ".json" extension too. you might do this:
# Opening JSON file
f = open('dbl.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data:
print(i)
# Closing file
f.close()```
The code is fine, however, it's good practice to add a file extension. Looks like you forgot to add the extension.
You are using relative paths. It is advised to use absolute paths. In this case, put the python script and db1 file in the same directory and try again.
In case, you want to debug just add the below code on top of your script to see if the file is present or not and modify the script accordingly.
import os;
print(os.listdir())
I have project in Pycharm, and I want to use json file that placed in this project.
How can I call it?
I use this one:
import json
file = open('~/PycharmProjects/Test/JSON_new.json')
x = json.load(file)
And received the following error:
FileNotFoundError: [Errno 2] No such file or directory: '~/PycharmProjects/Test/JSON_new.json'
But path is correct
EDIT: I understood what is the problem. Instead of json file txt was created (but I selected json). It creates txt files, maybe, someone knows hot to solve it? I can create only .py files directly. Other files no.
Is it correct if I create scratch json file and placed it in Scratches?
You may like to use following path(In linux):
file = open('/home/<user>/PycharmProjects/Test/JSON_new.json')
Replace user with your username. You need to know the correct path to the file, for which you can user PWD command in terminal.
You can use json module for this. You can open the file in a seperate object and pass it to json.load if you have a JSON string use json.loads.
import json
file = open('/path/to/json/file.json')
file_opened = json.load(file)
My current python script is like this:
import csv
with open ('2017_IL_sales.csv','r') as infile:
reader=csv.reader(infile)
with open('2017_IL_sales_report.csv') as outfile:
writer=csv.writer(outfile)
dict_report={rows[1]:rows[2] for rows in reader}
print dict_report
In brief, I want to open a csv file called 2017_IL_sales then create a dictionary for two columns inside. But with whatever reason, everytime I run the code via IDLE it told me this IOError: [Errno 2] No such file or directory: '2017_IL_sales.csv'. Anyone knows the reason?
Make sure that the script you are running is in the same folder as the file you are trying to read. If that is not possible, make sure to specify the correct file path.
Is IDLE's working directory that folder?
Run this in IDLE and see what you get:
import os
os.getcwd()
Currently I am trying to read in a csv file using the csv module in python. When I run the piece of code below I get an error that states the file does not exist. My first guess is that maybe, I have the file saved in the wrong place or I need to provide pyton with a file path. currently I have the file saved in C:\Documents and Settings\eag29278\My Documents\python test code\test_satdata.csv.
one side note im note sure wether having set the mode to 'rb' (read binary) was the right move.
import csv
with open('test_satdata.csv', 'rb') as csvfile:
satreader = csv.reader(csvfile, delimiter=' ', lineterminator=" ")
for row in satreader:
print ', '.join(row)
Here is the errror code.
Traceback (most recent call last):
File "C:/Python27/test code/test csv parse.py", line 2, in <module>
with open('test_satdata.csv', 'rb') as csvfile:
IOError: [Errno 2] No such file or directory: 'test_satdata.csv'
Your code is using a relative path; python is looking in the current directory (whatever that may be) to load your file. What the current directory is depends on how you started your Python script and if you executed any code that may have changed the current working directory.
Use a full absolute path instead:
path = r'C:\Documents and Settings\eag29278\My Documents\python test code\test_satdata.csv'
with open(path, 'rb') as csvfile:
Using 'rb' is entirely correct, the csv module recommends you do so:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
Windows is such a platform.
You can hit this error when you're running a Python script from a Directory where the file is not contained.
Sounds simple to fix, put the CSV file in the same folder as the .PY file. However when you're running under an IDE like VSCode the command output might cd to another directory when it executes your python file.
PS C:\git\awesome> cd 'c:\git\awesome'; ${env:PYTHONIOENCODING}='UTF-8'; ${env:PYTHONUNBUFFERED}='1';
& 'C:\Program Files (x86)\Python37-32\python.exe' 'c:\Users\jeremy\.vscode\extensions\ms-python.python-2019.9.34911\pythonFiles\ptvsd_launcher.py'
'--default' '--client' '--host' 'localhost' '--port' '1089'
'c:\git\Project\ReadCSV.py'
See how I'm in my awesome repo and the first command is: cd 'c:\git\awesome';
Then it executes the python file: 'c:\git\Project\ReadCSV.py'
So its expecting the CSV file in 'c:\git\awesome'.
To fix it, either use the full file names or CD to the directory containing the CSV file you wish to read.
Your current guess is right: either put the file in your test code directory or point python to the right path.
Make a fresh rename of your folder. That worked for me.