open() function cannot locate files - python

I’m a fairly new python user and I’m having an issue with the open() function where python isn’t able to find the files that I’m trying to work with. I’m using Python 3.5, PyCharm CE and macOS Sierra. I have a feeling the issue is caused by the fact that I’m using a mac and macs come preinstalled with python 2.7, which has caused me issues with things like adjusting filepaths and installing packages in the past.
Here’s what I’ve tried so far:
Referencing just the file name:
file = open("file_name.txt", "r").read()
Referencing the file from within the folder its in (on my desktop)
file = open(“folder_name/file_name.txt", "r").read()
Referencing the entire file path:
file = open("/Users/username\ 1/Desktop/folder_name/file_name.txt", "r").read()
Creating a new directory within the project and manually
adding files I’m trying to reference to the new directory:
print (os.getcwd())
>>> Users/username/PycharmProjects/Project_Name
os.mkdir(“directory_name”)
file = open("/Users/username/PycharmProjects/Project_Name/directory_name/file_name.txt", "r").read()
adding both the file while both in the folder sitting on my desktop and sitting alone on my desktop to the filepath
sys.path.append("/Users/User_Name\ 1/Desktop/Folder_name/File_name.txt")
sys.path.append("/Users/User_Name\ 1/Desktop/file_name.txt")
I’m getting basically this error message or some variation of it:
FileNotFoundError: [Errno 2] No such file or directory: ‘file_name.txt'
Thank you very much!!

>>> print (os.getcwd())
Users/username/PycharmProjects/Project_Name
So that's your current working directory. If you want to open a file that's on the desktop, you're going to have to tell Python that's where it is.
You can indicate your home directory ("/Users/username" on OS X or "/home/username" on Linux systems) with "~". Prove it in Python with:
>>> os.path.expanduser('~')
"/Users/username"
>>> os.path.expanduser('~/Desktop')
"/Users/username/Desktop"
So to open a file that's on your desktop, you can point Python to it with:
open(os.path.expanduser('~/Desktop/filename.txt'))

Related

1st Python file creation in Notepad on Windows getting error

So I've read through countless people asking similar questions but none seemed to be the answer I was needing.
Tonight I started the W3 Python tutorial. I downloaded the latest version of Python.
The first task is to go into a text editor, in this case I chose Notepad. I copied the following:
print("Hello World!")
and saved that as helloworld.py
I made sure it was in my C: drive... which is the only one I have anyway.
I used cmd.exe and typed in C:\Users\MyName>python helloworld.py
And I get the error: python: can't open file 'C:\Users\18327\helloworld.py': [Errno 2] No such file or directory
It is saving into my documents folder, is that the issue?
Your file's directory is 'C:\Users\18327\Documents\helloworld.py', while your directory specified in cmd is 'C:\Users\18327\helloworld.py'. Instead, run cmd in the Documents folder.

FileNotFoundError: [Errno 2] No such file or directory: 'test_text.txt'

The file "test_text.txt" is in the same folder as the program. it's a seperate folder from everything else that just has the text file and the program. unless I am misunderstanding what the error means, I just can't figure out what i'm missing or did wrong. i'm just reading a basics python book and this I pretty much copied it 1 for 1.
CODE
with open('test_text.txt') as test_text:
reader = test_text.read()
print (reader)
FileNotFoundError means you are trying to open a file that does not exist in the specified directory (in this case, whatever directory you are running your Python script from).
the file "test_text.txt" is in the same folder as the program. it's a seperate folder from everything else that just has the text file and the program
In that case, you need to make sure that you're in the same directory as your file on your command-line, or specify the full path to test_text.txt (e.g. /home/user/Desktop/test_text.txt)
FileNotFoundError occurs when you are trying to access files outside the scope of the application. In this case, the scope of your application is the folder in which you main python file resides.
There are couple of ways through which you can resolve this:
1. Provide an absolute or full path to the file: As mentioned by #pigeonburger in his answer, you can provide a full path. If you are using windows, then full path will be from C:/Desktop/
2. Using a Relative Path: Relative paths is the solution if both the file you want to access and the python program are in the same folder. Relative Paths start with ./ So, based on your file structure, the possible solution is this:
with open('./test_text.txt'):
# your code
Thank you Pointman for your answer. It did not work for me but it did lead me to what worked. I am using Visual Studio Code and I was having this issue with opening a text from a Udemy course.
jabber = open('Jabberwocky.txt', 'r')
for line in jabber:
print(line)
jabber.close()
After running this code I would get the following error message
FileNotFoundError: [Errno 2] No such file or directory: './Jabberwocky.txt'
I tried both the absolute path and the relative path option but they did not work for me. What I found that worked was once the terminal is open using Python you will have to traverse through your files until you get to the said folder or file. Once you do this then run the code and it will work.

VScode isn't creating a file with python

I'm using this code to create a file with "AAA" written in it. It's working in the regular python IDLE but isn't working in VScode.
with open("another.txt","w") as myfile:
myfile.write("AAA")
If no error is reported, then the file is successfully created somewhere. As you are using a relative path the file is probably saved to current working directory.
You can find it either via the path displayed in the terminal you are using, or in your Python code:
from pathlib import Path
print(Path.cwd())

Debugger Differences: VSCode / Terminal (Python)

I simply wanted to read a JSON file using this code:
import json
with open("file.json") as File:
print(json.load(File.read()))
When I try to run it using the VSCode debugger, I get the error:
[Errno 2] No such file or directory: 'file.json'
But when I run it from the Terminal using python file.py it works.
The problem is, that VSCode somehow uses an other "Working Directory" because when I run os.getcwd() in VSCode, I get the path to the parent folder of the folder the python script is in.
When I run it from the Terminal, I get the right path.
Why is that?
Just to point out: the problem is NOT the print statement/json. The same error shows up when I only try to open the file without anything else and then pass.
import os
dir_path = os.getcwd()
Use this to get your current directory. You'll be able to discern where Python is running from. You can also use the full filepath for your JSON file.
import json
with open("fullpath/to/json/file/file.json") as File:
print(json.loads(File.read()))
As discussed in comments, your problem turned out to be the environment you were working in. When the program was executed from terminal, it worked and found the file. That is most likely because of the way your virtual environment is set up in VS Code. A virtual environment or venv as it is called, is an isolated environment of Python interpreter separate from your global Python install. It is useful when you are working on two different projects that require different versions of libraries. For example; a project that uses Django 1.10 and one that uses 1.9, so you don't have to keep shuffling between installing and uninstalling them.
A virtual environment is a directory tree which contains Python
executable files and other files which indicate that it is a virtual
environment.
As explained here, your .json file was most likely outside of your project virtual environment, and that is why it could not find it. I hope that helps you understand it.
You can verify if a file exists using os package:
import os.path
print(os.path.isfile("file.json"))
this should print True if the file exists.
Also you can try using the absolute path to make sure.
import json
with open('/Users/my_pc/Downloads/example_2.json') as f:
data = json.load(f)
print(data)
you can load your json by this way and give exact path of your directory
where your json file is present.

How do I read a text file in Pydev?

I'm doing a school assignment that requires me to read a file. I chose to use the Eclipse and Pydev combination because I really like the environment. However, no matter where I place the .txt file I get the following error: FileNotFoundError: [Errno 2] No such file or directory: 'file.txt' I've tried placing it in the src folder and the file directory. Something that I find quite odd is that if I were to run the same python module in IDLE, the file is found and read perfectly. Any help is appreciated!
You should put the file in the same folder as your .py file, if that doesn't work try to find out what directory it's currently using os.getcwd().
To fix this specifically:
Open Run Dialog...-> Select your run configuration->Arguments Tab->Working directory
EDIT:
import os
print os.getcwd()
If you cannot determine where to place your file - place it anywhere and use absolute path:
print(open(r'c:\your_file.txt', 'r').read())
If you've not played with your eclipse too hard you can just place your_file.txt in your project directory and use:
print(open('your_file.txt', 'r').read())
Update:
From one of your comments I've seen that you are doing sth extremely weird - look here:
You've somehow managed to open python.exe in your console window within eclipse and you edit files with eclipse but run it from python.exe directly on right hand side hence your code on the left has different environment if executed from eclipse and different when executed from right handside window.
Close that console and push PLAY button in your ECLIPSE:
You better first edit your files in something easier like notepad++. Just create your python source within directory whrer your python.exe resides and run that from command line with:
python.exe yoursource.py
Once you get a hang of how things work - switch to eclipse.
While working in notepad++ follow python tutorial
You simply are trying to do too many unknown to you things at the same time - this way you'll be scratching your head all day long
Pydev in Eclipse default working directory
Took me 10 seconds to find ;)
When you run your script from console it's this file directory, but from eclipse it could be another.

Categories

Resources