Opening and Reading files in Python [duplicate] - python

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 3 months ago.
For some reason I am unable to open my .txt file within python.
I have the .py and .txt file within a folder. Both files are stored Workspace -> Folder(Crash Course) -> Folder(Lessons) -> Folder(Ch 10)-> both files within this Ch 10 Folder.
I am getting
FileNotFoundError: [Errno 2] No such file or directory: 'pi_digits.txt'
With the code:
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)

This is less for the person that asked the question but more for people like myself that come here from Python Crash Course with the same question and don't get the answer they were looking for:
If, like me, you were running the code from your text editor (in my case VS Code), it's possible that the terminal window within the editor wasn't in the proper directory. I didn't realize myself, because I was thinking that because I opened the .py file from the correct working directory in the terminal that everything should work as planned. It wasn't until I realized that the terminal in the editor is a separate instance (thus making the present working directory home instead of my folder for PCC work) that I was able to get the program to run as intended.
In short, navigate to the proper directory in your editor's terminal instance and the program should run as intended.
Hope this helps!
image with terminal open on desktop and in text editor to show working directory difference

I used full path of the file along with r, which is for raw string. Worked for me.
example:
filename = **r**'C:\Python\CrashCourse\pi_digits.txt'
with open(filename) as file_object:
content = file_object.read()
print(content)

The path to the file is relative to where you run the python file from, not from where the python file is located.
Either run your code from the same directory as the files, or make the file path absolute, based on the python file's location.
import os
with open(os.path.join(os.path.dirname(__file__), 'pi_digits.txt')) as file_object:
contents = file_object.read()
print(contents)
Hope that helps

Try this:
with open('c:\\Workspace\\Crash Course\\Lessons\\Ch 10\\pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)

You can try getting the full path to the file
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
pi_digits = os.path.join(dir_path, 'pi_digits.txt')
with open(pi_digits, r) as file_object:
print(file_object.read())

You might have to enable "Execute in file dir"
vscode setting

Related

Reading file in python on the Mac

I am very new on this platform and I need help reading a file in python. First, it was a docx file because I am using Mac, I converted it into a txt file ,but still have file not found error.
Here is some code:
opdoc = open('PRACT.txt')
print(opdoc.readline())
for each in opdoc :
print(each)
and this the error output: FileNotFoundError: [Errno 2] No such file or directory: 'PRACT.txt'
Unless your file is in the exact same directory as your python file, you'll get this error. Even then, it's best practice to include some sort of relative filepath, like "./PRACT.txt". In general, your issue stems from the fact that Python doesn't know where to look for your file, and where it does know to look, the file isn't there. You need to provide the full path to the file, like:
with open("path/to/file/PRACT.txt", "rb") as f:
# read file etc
Make a new folder and put the txt file in it and also the programme itself. Or just put them in the same directory.
As you have this error ( No such file or directory: 'PRACT.txt') your code couldn't find the file because they were not in the same directory. When you use open("README.txt") the programme is assuming that the text is in the same directory as your code. If you don't want them in the same directory you could also try open(f"[file_path]") and that should work.

No such file or directory using Python [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
How do you properly determine the current script directory?
(16 answers)
Closed 6 months ago.
I am trying to write a program in python where it reads a list of usernames from a file and sends a request to instagram to see if the username is available or not. Then it should prompt a message saying "THIS USERNAME IS AVAILABLE" or otherwise "THIS USERNAME IS TAKEN". I am having an error when trying to read my file that states 'FileNotFoundError: [Errno 2] No such file or directory: 'list.txt', even though the file is in my folder where the program resides.
I am also fairly new to python.
Here is my code currently:
import requests
filepath = 'list.txt'
separator = "\n" #Every time you use a newline it detects it as a new user
list = open(filepath, "r").read().split(separator)
notTaken = []
for i in list :
response = requests.get("https://instagram.com/" + i + "/")
if response.status_code == 404 :
notTaken.append(i)
It worked in my case. My list.txt was in the same directory as my python file
import requests
with open('list.txt','r') as f:
data = f.read().split("\n")
for i in data:
pass
#...(write the rest of the code)
Use the absolute directory for that file i.e /home/directory/file_name if you are using window else use c:\\\\directory\\file_name
this is if the file is not in the current working directory of the terminal. If you are in the same directory of the file in the terminal, use./file_name
Since the file is in the same directory as your program, your code will only work if the current working directory is also that same directory. If you want to run this program from anywhere, you need a way to find that directory.
When python executes a script or module it adds a __file__ variable giving the path. (Extension modules and modules in compressed packages may not have this variable). The __file__ path can be relative to the current working directory or absolute. The pathlib library gives us a handy method for working with paths. So,
from pathlib import Path
separator = "\n" #Every time you use a newline it detects it as a new user
filename = 'list.txt'
# get absolute path, then parent directory, then add my file name
filepath = Path(__file__).resolve().parent/filename
mylist = filepath.open().read().split(separator)
Since a "\n" newline is used to demark the file, you don't need to split it yourself. You could do this instead
mylist = filepath.open().readlines()

Confusing problem >> FileNotFoundError: [Errno 2] No such file or directory:

This problem puzzled me.
Maybe the problem is in the code, I hope you take a look
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
He says that the file does not exist
FileNotFoundError: [Errno 2] No such file or directory: '\\Desktop\\project\\data\\generated\\training_images_labels.txt'
Though the file exists
I need solutions
If it says that the file does not exist though the file exists, it means the path has been not given properly. Try giving the path correctly.
Method 1:
Giving correct path 'C:\\Users\\Public\\Desktop\\project\\data\\generated\\training_images_labels.txt' or
'C:\\Users\\<insert your username>\\Desktop\\project\\data\\generated\\training_images_labels.txt' is your path if I guess correctly
Method 2:
Using os module ( Recommended )
mydir = 'C:/Users/Public/Desktop/project/data/generated'
myfile = 'training_images_labels.txt'
training_images_labels_path = os.path.join(mydir, myfile)
with open(training_images_labels_path,'r') as file:
lines = file.readlines()
Method 3:
You can also try changing the working directory to the location where your data is present. ie Desktop>project>data>generated here and open the file with file name. ie
with open('training_images_labels.txt','r') as file:
lines = file.readlines()
I had the same problem with importing an excel file, which of course exists in the same directory with my .py file. The chosen solution above did not help me, and actually I didn't understand those three methods, as I am working on mac OS.
This method worked for me: in Spyder, I usually run the file by pressing the keys "Shift + Enter", which in this case made the problem. So, my solution was, to press on the "Run file" button (or the fn+F5 key) instead.
Maybe someone wants to explain the difference.
Looks like its a windows path you are working and i believe path really thrown in the error is wrong when compared to the actual where the txt file resides.. just cross check once, if that's the case try to pass the correct path in to the variable "training_images_labels_path"
Can you tell how you created this path.Some advise.
use path separator library to generate path to avoid this error.
training_images_labels_path
further try to navigate parent directory using python and print pth.may be some new line or linux/windwos convereted path or other special character in path. navigating parent directory and listing will solve
if still not solve try to navigatep parent-parent dir and print path
try hard
Watch your path if its correct or not. I had the same problem and it turned out i didnt had the good path set

Python can't find where my txt file is, how can i link it or where do i need to put the file?

Python can't find where my .txt file is, how can I find the correct path to it or where do I need to put the file?
I tried the following but got an error:
with open("C:\Users\raynaud\Downloads\notlar.txt","r",encoding="utf-8") as file:
with open("dosya.txt","r",encoding= "utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'dosya.txt'
If you are not using absolute path, you must place the file in the same directory as the script is. On absolute paths you should not use \ like "C:\Users\UserName\", because \ is the escape character in Python (and many more languages). You must use it like this: "C:\\Users\\UserName\\"
Have you checked your current directory? It might be pointing to somewhere unexpected. Try:
import os
os.getcwd()

How to write a whole string to a file in Python and where does the file go?

I am doing an assignment on text formatting and alignment (text wrapping) and I need to write my formatted string to new file. But once I have written to the file (or think I've written) where does that file go? Does it actually create a file on my desktop or am I being stupid?
This is my code:
txtFile = open("Output.txt", "w")
txtFile.write(string)
txtFile.close()
return txtFile
Cheers,
JT
The text is written to a file called "Output.txt" in your working directory (which is usually the directory from which the script has been executed).
To display the working directory, you can use:
>>> import os
>>> os.getcwd()
'/home/adam'
When you open a file without specifying a file path, the file will be created in the python scripts working directory.
Usually that is the location of your script but there are times when it may be a different place.
The os module in python will provide functions for checking and changing the working directory within python itself.
most notably:
os.chdir(path)
os.fchdir(fd)
os.getcwd()
It will create a new file called "Output.txt" in the same directory that you executed your script from. It may mean that the file can't be written to, if you're in a directory that doesn't have the appropriate permissions for your user.

Categories

Resources