Python calling .txt file in same folder - python

I'm trying to access the .txt file in my project folder (in the same folder). But I am kept getting FileNotFoundError: [Errno 2] No such file or directory: '\u200e\u2068useragents.txt' error.
Code is;
USER_AGENT_LIST = "‎⁨useragents.txt"

it seems like you have a control character in your file name value. erase and write the file name again. Check if your editor or IDE has the feature to show invisible control characters. you will be able to see it.

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.

PyCharm can't seem to find .txt file

I am a n00b programmer and I have a python program that reads a text file in the same folderas itself. PyCharm can't seem to find that text file. Does anyone know why?
My program:
password_file = open('passwords.txt', 'r')
print(password_file.read())
password_file.close()
PyCharm can't seem to find the text file - the error message:
C:\Users\User\AppData\Local\Programs\Python\Python38-32\python.exe C:/Users/User/PycharmProjects/password_test/password.py
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/password_test/password.py", line 1, in <module>
password_file = open('passwords.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'passwords.txt'
Process finished with exit code 1
Like I said, the python program (password.py) is located in the same folder as the text file (passwords.txt). The main reason I find this strange is because I have set a program up like this before and it worked just fine. However, when I use a full path, like so:
password_file = open('C:/Users/User/PycharmProjects/password_test/passwords.txt', 'r')
print(password_file.read())
password_file.close()
my program prints the text file just fine.
What's going on and, more importantly, how do I fix it?
Thank you in advance and have a nice night.
File is opened relative to your working directory. It doesn't matter where your "password.py" is, it only matters where are you running your "python.exe" from. If you use command line to start it, then you should navigate into directory with that file. If you're using PyCharm - you can set "Working directory:" inside "Run/Debug Configurations" window from "Run -> Edit Configurations...".

Cannot access file in current working directory - 'FileNotFoundError: [Errno 2] No such file or directory'

I have seen multiple other questions regarding this but none that answer my question. I am getting the error
'FileNotFoundError: [Errno 2] No such file or directory:' even though my current working directory matches that of the location of the file.
I have tried hardcoding the file location using python ex15.py C:\Users\Matt\py\sample.txthowever i get 'FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Matt\\py\\sample.txt'
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your filename {filename}:")
print(txt.read())
print("Type the filename again")
file_again = input("> ")
variable
text_again = open(file_again)
print(txt_again.read())
Current working directory is C:\Users\Matt\py. When I try to hardcode it gives two backslashes (\) which I assume is causing an issue, but I would like to be able to do it without hardcoding anyway.
Thanks.
The problem is that your file is not actually called sample.txt. Its real name is sample.txt.txt. It just happens to look like sample.txt in the GUI because you're using Windows and you've told Windows Explorer to hide extensions in file names.
See also:
https://blogs.technet.microsoft.com/activedirectoryua/2013/05/22/how-to-see-those-file-extensions-in-windows/
https://answers.microsoft.com/en-us/windows/forum/windows_10-files/how-to-display-file-extensions-in-w-10/226d323d-978a-47de-bd1d-8780643897e3

Opening and Reading files in Python [duplicate]

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

File does not exist error with 'w' mode

I am encountering an odd behaviour from the file() builtin. I am using the unittest-xml-reporting Python package to generate results for my unit tests. Here are the lines that open a file for writing, a file which (obviously does not exist):
report_file = file('%s%sTEST-%s.xml' % \
(test_runner.output, os.sep, suite), 'w')
(code is taken from the package's Github page)
However, I am given the following error:
...
File "/home/[...]/django-cms/.tox/pytest/local/lib/python2.7/site-packages/xmlrunner/__init__.py", line 240, in generate_reports
(test_runner.output, os.sep, suite), 'w')
IOError: [Errno 2] No such file or directory: './TEST-cms.tests.page.NoAdminPageTests.xml'
I found this weird because, as the Python docs state, if the w mode is used, the file should be created if it doesn't exist. Why is this happening and how can I fix this?
from man 2 read
ENOENT O_CREAT is not set and the named file does not exist. Or, a
directory component in pathname does not exist or is a dangling
symbolic link.
take your pick :)
in human terms:
your current working directory, ./ is removed by the time this command is ran,
./TEST-cms.tests.page.NoAdminPageTests.xml exists but is a symlink pointing to nowhere
"w" in your open/file call is somehow messed up, e.g. if you redefined file builtin
file will create a file, but not a directory. You have to create it first, as seen here
It seems like the file which needed to be created was attempted to be created in a directory that has already been deleted (since the path was given as . and most probably the test directory has been deleted by that point).
I managed to fix this by supplying an absolute path to test_runner.output and the result files are successfully created now.

Categories

Resources