If I have a .py (called p.py) folder where I have my code and I want to open a file which is a .json (called j.json) file and I have opened it as a folder next to the p.py folder. I want to read from the j.json make it a dictionary. It does not seem to work with this :
import json
with open("j.json") as f:
data = json.load(f)
output: FileNotFoundError: [Errno 2] No such file or directory
What am I doing wrong?
If p.py and j.json are at the same level, we can directly quote it as its name instead of its absolute path:
Turn to file explorer, View -> Select File name extensions, to check if the name of j.json is right, or we can say, to check if j.json exists:
Try the full path directory instead of just your file name. But you should put an r before the string. E.g.
with open(r'path_to_file/j.json') as f:
data = json.load(f)
When you specify a path (that is not absolute) it is relative to the directory you are executing Python in
Let's say I'm in my Terminal at directory C:/Users/Mathias/Desktop and I execute the following code with Python
with open("veryimportant.json", "r") as file:
for line in file:
print(line)
"veryimportant.json" will be relative to my working directory (C:/Users/Mathias/Desktop) so the absolute path will be C:/Users/Mathias/Desktop/veryimportant.json
So what can you do?
You have the following options.
Option 1
Move the j.json file to the same directory as your p.py file
Option 2
Refer to j.json with the absolute path (looks something like this "C:/path/to/file.json" with your drive letter first)
Related
This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 months ago.
I'm trying to write a simple program to read a file and search for a word then print how many times that word is found in the file. Every time I type in "test.rtf" (which is the name of my document) I get this error:
Traceback (most recent call last):
File "/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/How many? (Python).py", line 9, in <module>
fileScan= open(fileName, 'r') #Opens file
FileNotFoundError: [Errno 2] No such file or directory: 'test.rtf'
In class last semester, I remember my professor saying you have to save the file in a specific place? I'm not sure if he really said that though, but I'm running apple OSx if that helps.
Here's the important part of my code:
fileName= input("Please enter the name of the file you'd like to use.")
fileScan= open(fileName, 'r') #Opens file
If the user does not pass the full path to the file (on Unix type systems this means a path that starts with a slash), the path is interpreted relatively to the current working directory. The current working directory usually is the directory in which you started the program. In your case, the file test.rtf must be in the same directory in which you execute the program.
You are obviously performing programming tasks in Python under Mac OS. There, I recommend to work in the terminal (on the command line), i.e. start the terminal, cd to the directory where your input file is located and start the Python script there using the command
$ python script.py
In order to make this work, the directory containing the python executable must be in the PATH, a so-called environment variable that contains directories that are automatically used for searching executables when you enter a command. You should make use of this, because it simplifies daily work greatly. That way, you can simply cd to the directory containing your Python script file and run it.
In any case, if your Python script file and your data input file are not in the same directory, you always have to specify either a relative path between them or you have to use an absolute path for one of them.
Is test.rtf located in the same directory you're in when you run this?
If not, you'll need to provide the full path to that file.
Suppose it's located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you'd enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you'd enter
../some_other_folder/test.rtf
As noted above the problem is in specifying the path to your file.
The default path in OS X is your home directory (/Users/macbook represented by ~ in terminal ...you can change or rename the home directory with the advanced options in System Preferences > Users & Groups).
Or you can specify the path from the drive to your file in the filename:
path = "/Users/macbook/Documents/MyPython/"
myFile = path + fileName
You can also catch the File Not Found Error and give another response using try:
try:
with open(filename) as f:
sequences = pick_lines(f)
except FileNotFoundError:
print("File not found. Check the path variable and filename")
exit()
A good start would be validating the input. In other words, you can make sure that the user has indeed typed a correct path for a real existing file, like this:
import os
fileName = input("Please enter the name of the file you'd like to use.")
while not os.path.isfile(fileName):
fileName = input("Whoops! No such file! Please enter the name of the file you'd like to use.")
This is with a little help from the built in module os, That is a part of the Standard Python Library.
You might need to change your path by:
import os
path=os.chdir(str('Here_should_be_the_path_to_your_file')) #This command changes directory
This is what worked for me at least! Hope it works for you too!
Difficult to give code examples in the comments.
To read the words in the file, you can read the contents of the file, which gets you a string - this is what you were doing before, with the read() method - and then use split() to get the individual words.
Split breaks up a String on the delimiter provided, or on whitespace by default. For example,
"the quick brown fox".split()
produces
['the', 'quick', 'brown', 'fox']
Similarly,
fileScan.read().split()
will give you an array of Strings.
Hope that helps!
First check what's your file format(e.g: .txt, .json, .csv etc ),
If your file present in PWD , then just give the name of the file along with the file format inside either single('')or double("") quote and the appropriate operation mode as your requirement
e.g:
with open('test.txt','r') as f: data=f.readlines() for i in data: print(i)
If your file present in other directory, then just give the full path name where is your file is present and file name along with file format of the file inside either single('')or double("") quote and the appropriate operation mode as your requirement.
If it showing unicode error just put either r before quote of file path or else put '/' instead of ''
with open(r'C:\Users\soman\Desktop\test.txt','r') as f: data=f.readlines() for i in data: print(i)
The mistake I did was
my code :
x = open('python.txt')
print(x)
But the problem was in file directory ,I saved it as python.txt instead of just python .
So my file path was
->C:\Users\noob\Desktop\Python\Course 2\python.txt.txt
That is why it was giving a error.
Name your file without .txt it will run.
I don't know what's wrong here, all I'm trying to do is to open this file, but it says it can't find such a file or directory, however as I have highlighted on the side, the file is right there. I just want to open it. I have opened files before but never encountered this. I must have missed something, I checked online, and seems like my syntax is correct, but I don't know.
I get the same error when I try with "alphabetical_words" which is just a text file.
When open() function receives a relative path, it looks for that file relative to the current working directory. In other words: relative to the current directory from where the script is run. This can be any arbitrary location.
I guess what you want to do is look for alphabetical.csv file relative to the script location. To do that use the following formula:
from pathlib import Path
# Get directory of this script
THIS_DIR = Path(__file__).absolute().parent
# Get path of CSV file relative to the directory of this script
CSV_PATH = THIS_DIR.joinpath("alphabetical.csv")
# Open the CSV file using a with-block
with CSV_PATH.open(encoding="utf-8") as csvfile:
pass # Do stuff with opened file
You need to import csv. Then you can open the file as a csv file. For example,
with open ("alphabetical.csv", "r") as csvfile:
Then you can use the file.
Make sure the file is in your cwd.
I am new to VSCODE. I opened a text file via vscode and entered some details. Where can I find the file?
f=open('story.txt','w')
f.write('my name is')
f.write('my age is')
f.close()
f=open('story.txt', 'r')
print(f.readline())
f.close()
this is the output
However I cannot find 'story.txt' in file explorer. I used another text editor and then error came as file not found. but when i reopened the file in vs code I was getting a proper output.
From the screenshot you supplied it looks like you are running the script from C:\Users\<YourName>, then this is where your story.txt file will be.
To specify another location you need to supply the open() method with a full path
Also, it's best practice to close the file before opening it again for reading. also, you might want to use a context manager to help you with this
If you want your file saved in the directory of your script, you can use os and __file__ to locate your script's directory and use that.
import os
my_dir = os.path.dirname(__file__)
new_path = os.path.join(my_dir, 'story.txt')
print(new_path)
os documentation
__file__ explained
When you run python script it will execute from the current working directory by defaut.
If you want to be sure where your file will be, you may pass the complete file path instead of file name only (eg: C:\\filepath\\filename.txt)
or you can move to the desired directory before read/write with os.chdir(filepath)
If you don't know where the script is running you can use os.getcwd() to get this directory from your code
import os
print(os.getcwd()) #will show the current working directory
os.chdir("c:\\") #will move to C:\ directory
f=open('story.txt','w')
f.write('my name is')
f.write('my age is')
f=open('story.txt', 'r')
print(f.readline())
f.close()
When you create a file with Python, the file will be create in the same folder as your script. So, if your folder all_python_scripts contains your script, your file story.txt will be created in this folder. Try to search your file in the script's folder.
I can write to a file in current directory.
I cannot write to a file in a subdirectory.
I checked online but the posts and previous questions didn't really help.
I have the code below, it should write to File.txt which is inside Subfolder. However, instead of this, I get a new File called "SubFolder\File.txt" in my current directory.
Any help?
PATH = os.getcwd()
PATH+= 'SubFolder\File.txt'
fileInput = open(PATH, "w")
fileOutput = open("SubFolder\File.txt", "w")
I expect a file in a subfolder.
I get a file with the desired path as a file name. Can you help? Thanks!
use double escape for file paths.
fileOutput = open("SubFolder\\File.txt", "w")
Opening a file for writing doesn't create any intervening subfolders that don't yet exist. You have to create them yourself first, using os.mkdir() (for one level) or os.makedirs() (for multiple levels).
I'm trying to load the json file but it gives me an error saying No such file or directory:
with open ('folder1/sub1/sub2/sub2/sub3/file.json') as f:
data = json.load(f)
print data
The above file main.py is kept outside the folder1. All of this is kept under project folder.
So, the directory structure is Project/folder1/sub1/sub2/sub2/sub3/file.json
Where am I going wrong?
I prefer to point pathes starting from file directory
import os
script_dir = os.path.dirname(__file__)
file_path = os.path.join(script_dir, 'relative/path/to/file.json')
with open(file_path, 'r') as fi:
pass
this allows not to care about working directory changes. And also this allows to run script from any directory using it's full path.
python script/inner/script.py
or
python script.py
I would use os.path.join method to form the complete path starting from the current directory.
Something like:
json_filepath = os.path.join('.', 'folder1', 'sub1', 'sub2', 'sub3', 'file.json')
As always, an initial slash indicates that the path starts from the root. Omit the initial slash to indicate that it is a relative path.