opening a .txt file - python

first, i'd like to mention that im using python via visual studio. not sure if this information will
be relevant but this is my first time using file input so i'm not sure
basically, i have a .txt file located in the same location as my .py file. however, when i go to access it, i get an error 'FileNotFoundError: [Errno 2] No such file or directory'
is there a way to make it work or a different IDE i should use?
I tried reading a .txt file from the same location as my .py file. however, i keep getting the error 'FileNotFoundError: [Errno 2] No such file or directory'

Take into account that the script might not be running from the same path where your python script is and most probably your are not specifying the exact path of the file.
If your file is located in the same directory where your python sript is you can use the pathlib library this way to get your script to work:
import pathlib
# Some custom code
# find your current script path
current_script_path = pathlib.Path(__file__).parent
my_file_name = "my_file_name.txt"
# Specify the file path relative to your script's path
my_file_path = current_script_path / my_file_name
with open(my_file_path, "r+") as f:
print(f.read())

Related

open with not creating and writing file

I am following a tutorial (Beautiful Soup) and I can't seem to get open with to create a .txt file as I am getting this error:
with open(f'posts/{index}.txt', 'w+') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'posts/1.txt'. I tried looking up different solutions to my problem currently running python 3.9. Is there another step I need to correct this issue?
The interpreter isn't finding the directory "posts" in your current working directory. If it exists, you are not in its parent directory. Try using the full path, e.g. rf'C:\users\myuser\posts\{index}.txt' or rf'~/posts/{index}.txt' on linux.
Or, if it doesnt't exist, add these lines:
import os
os.mkdir('posts')
You can find your current working directory this way:
import os
os.path.abspath('.')

FileNotFoundError in Python Visul Studio

I get this when I try to run my python project code
with open("config.json", "r") as f:
Exception raised:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
what is a solution for this?
here is a screenshot of the code and everything.
the file config.jason needs to be in your current working directory to be found by open if you do not use a full path. Your cwd is probably where you launched python. To check do
import os
print(os.getcwd())
Your easiest solution is probably to use a full path name for the file.
As shown in the screenshot of the IDE, you should exactly point out where the .json file. Now the json file and python code are not located in the same folder.
FYI, there are two types of path, absolute path and relative path. Please see https://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-pythonhttps://www.kite.com/python/answers/how-to-find-the-absolute-and-relative-path-of-a-file-in-python
with open("/file program/config.json", "r") as f
content = f.read()
# do something
Or, just move out the config.json file to the folder, which the python code is located.

Call a file in another folder in Eclipse for Python project

I have a small enough Python project in Eclipse Neon and keep getting the same error and can't find proper documentation on how to solve. In my main I need to call a file that is located in another folder. The error I receive is IOError: [Errno 2] No such file or directory:
I have an empty init.py file in the folder (XML_TXT) that I'm trying to use.
It looks like Groovy is importing okay, or else you would get an ImportError. An IOError indicates that it can't find "test.txt". Does that file exist?
It will work if the file path is relative to where you are running the script from. So for example if test.txt is in a folder
Groovy("folder_name/test.txt")
You can also go up in the directory structure if you need to, for example
Groovy("../folder_name/test.txt")
Or, if you want to be able to run the file from anywhere, you can have python work out the absolute path of the file for you.
import os
filename = os.path.join(os.path.dirname(__file__), 'folder_name/test.txt')
u = Groovy(filename)

Where does Python search for files when using open?

I have the simplest file opening line in my code.
file = open("file.txt", "r+")
Where does python search for files? The only location that works for me is
C:/Users/useraccount
file = open("file.txt", "w")
This also creates the file in that specific location.
It won't open the file if the file is in the exact same folder as the python script itself.
Also, if I make it
file = open("folder/file.txt", "r+")
it will not open the file if the file is in C:/Users/*useraccount*/folder.
Is it possible to open files that aren't in that specific location?
If you pass a relative path, like file.txt, Python will search for that file relative to the same directory where you are running the command from.
If you are in - C:/Users/useraccount/ and you try to open file.txt then Python tries to open C:/Users/useraccount/file.txt.
Similarly, if it's folder/file.txt then Python tries to open C:/Users/useraccount/folder/file.txt
You should always try to get the absolute path of a file by using the different functions in the os.path module.
If you use relative paths, they will be relative to the current working directory. To find out the current working directory, run the following code snippet from Python.
import os
print os.getcwd()
To avoid this, specify the absolute path.

Full File Path vs. Short OSX

I'm running OSX Mavericks but this problem has been going on since I had Snow Leopard.
When writing a script in any language, eg: Python. When I try to open a file the short
form doesn't work.
file = open('donkey.jpg')
And I get this error:
IOError: [Errno 2] No such file or directory: 'donkey.jpg'
Instead, I always have to specify the full path.
file = open('/Users/myName/Desktop/donkey.jpg')
Any ideas on why this could be happening and how to correct it?
If you specify donkey.png, it means donkey.jpg file in the current working directory. (relative path)
Make sure you're running the script in the same directory where donkey.jpg exists.
If you want specify the image file path relative to the script file instead of current working directory use following:
import os
filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'donkey.jpg')
NOTE You can use __file__ only in script file. (not in interactive mode)
Your open call does not have a mode parameter. In which case, it defaults to opening the file in read mode.
Unless the file you are opening (to read) resides in the current working directory, it is completely expected that the python script throws a IOError.

Categories