Issue using open() in Python 3.2.3 - python

I am having issues with the open() function in Python 3.2.3. The following code works well using 2.7.3, but not with Python 3:
file = open("text.txt", 'r')
In Python3, it gives me a standard IOError:
IOError: [Errno 2] No such file or directory: 'text.txt'
Note that the text.txt file that is referenced is in the same directory as the python file.
Any ideas?

The file name is not relative to the directory of the file, but your current working directory (which you can find out with os.getcwd()).
If you want to open a file whose name is relative to your Python file, you can use the magic variable __file__, like this:
import os.path
fn = os.path.join(os.path.dirname(__file__), 'text.txt')
with open(fn, 'r') as file:
# Do something, like ...
print(file.read())

You are trying to open a file in read mode, and this file has to exist.
Perhaps problem is that the file just doesn't exist in your python3 path and therefore the open command fails, but 'text.txt' exist on your python2.7 lib (or somewhere in python2.7 path) and this is why python is able to locate the file and open it.
You can just try this code (this will assure you the file exist since you create it):
f = open('text.txt','w')
f.close()
f.open('text.txt','r')

I was using Eclipse with Pydev, and had the text.txt file within the package instead of on the project level. To access a file within the package, you need to use:
file = open("[package]/text.txt", 'r')

Related

opening a .txt file

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())

CSV not detecting file within same folder as program

I'm currently doing an assignment that requires me to use CSV files in Python. I have the .csv file in the same directory as the program itself, yet it gives me the same "No such file or directory" error.
I am sure the name is not a problem. This problem has happened to me before with another file and I wasn't able to fix that either.
Code:
with open('file.csv') as file:
content = csv.reader(file, delimiter=',')
FileNotFoundError: [Errno 2] No such file or directory: 'file.csv'
I fixed this by using the OS library for python.
Change the current working directory with:
os.chdir(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))))
This changes Python's working directory to the one that your file is contained in.

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.

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.

How to have Windows Explorer return the path of a file as a string in Python?

Background
I am working on a basic text editor, and need to use Windows Explorer to get the path of a file. This is my code currently, but it simply opens the file - I need it to return the path as a string:
import subprocess
subprocess.Popen(r'explorer /select, "C:\"')
Question(s)
How would I have it return the path as a string?
How would I use the path to access a specific file? For instance, if I wanted to open file myFile, but it wasn't in the same folder as my program, how would I have it access that file, in a different folder? Sorry for the ambiguity!
Tech Specs
OS: Windows 7
Language: Python 2.7.3
I would not recommend using Windows Explorer for this purpose, you might want to look at Tkinter. This is very close to this other question.
The main reason for using a third party library is that python runs on multiple platforms. Choosing a file on OSX and Windows 7 and Ubuntu is of course pretty different. This is the main reason why it is not part of the python runtime.
About question 2, to open a file located in the process working directory, you could use:
file = open('filename.txt', 'r')
To open a file which is in a different directory, you can use:
directory = 'C:\Users\MyName\Documents\example.txt'
file = open(directory, 'r')
That would also work, opening the file at the directory specified. If there is no such file in the directory, you would get the following error:
File "filename.py", line #, in <module>
file = open('filename.txt', 'r')
IOError: [Errno 2] No such file or directory: 'filename.txt'

Categories