I'm having trouble opening a Python file :( - python

I saved a file as DictionaryE.txt in a Modules folder I created within Python. Then I type:
fh = open("DictionaryE.txt")
I get this error message:
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
fh = open("DictionaryE.txt")
IOError: [Errno 2] No such file or directory: 'DictionaryE.txt'
What am I doing wrong? Could someone please describe a specific, detailed step-by-step instruction on what to do? Thanks.

As other answers suggested, you need to specify the file's path, not just the name.
For example, if you know the file is in C:\Blah\Modules, use
fh = open('c:/Blah/Modules/DictionaryE.txt')
Note that I've turned the slashes "the right way up" (Unix-style;-) rather than "the Windows way". That's optional, but Python (and actually the underlying C runtime library) are perfectly happy with it, and it saves you trouble on many occasions (since \, in Python string literals just as in C ones, is an "escape marker", once in a while, if you use it, the string value you've actually entered is not the one you think -- with '/' instead, zero problems).

Use the full path to the file? You are trying to open the file in the current working directory.

probably something like:
import os
dict_file = open(os.path.join(os.path.dirname(__file__), 'Modules', 'DictionaryE.txt'))
It's hard to know without knowing your project structure and the context of your code. Fwiw, when you just "open" a file, it will be looking in whatever directory you're running the python program in, and __file__is the full path to ... the python file.

To complement Alex's answer, you can be more specific and explicit with what you want to do with DictionaryE.txt. The basics:
READ (this is default):
fh = open("C:/path/to/DictionaryE.txt", "r")
WRITE:
fh = open("C:/path/to/DictionaryE.txt", "w")
APPEND:
fh = open("C:/path/to/DictionaryE.txt", "a")
More info can be found here: Built-in Functions - open()

Related

Why does Python not like double underscore in a python string do?

I've been reading about mangling and what double underscores do in Python, but does all that apply with a string field inside single quotes?
In code sample below,
'C:\\Apps\\Quotes\\data\\GetQuoteslog__2020_08_11.txt' fails
but
'C:\\Apps\\Quotes\\data\\GetQuoteslog_2020_08_11.txt' works.
def log_message(logFilename, logMessageText):
#logFilename = "./data/GetQuotesStoreBlobs_log.txt"
file1 = open(logFilename, "a") # append mode
file1.write(logMessageText + "\n")
file1.close()
filename = 'C:\\Apps\\Quotes\\data\\GetQuoteslog__2020_08_11.txt'
print("filename=" + filename)
log_message(filename, "Test permission error")
Error is either a permission denied or the following (depending on whether file pre-exists or not):
Traceback (most recent call last):
File "C:/Apps/Quotes/testLog.py", line 11, in <module>
log_message(filename, "Test security")
File "C:/Apps/Quotes/testLog.py", line 4, in log_message
file1 = open(logFilename, "a") # append mode
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Apps\\Quotes\\data\\GetQuoteslog__2020_08_11.txt'
Edit/Update:
I think I changed the path name to simplify a longer path name, and thus my code does not reproduce now, when I put in the correct directory name. I think I assumed the double underscores was the problem.
But this was part of much larger program, which started getting that error when I added the date time to my log filename. I might have jumped to conclusions, but unfortunately cannot reproduce at this time.
I don't think the double underscores was the problem at all.
Python doesn't have a problem opening files with double underscores. If you're getting a permissions error, it's because the file is already opened somewhere. If you don't have it opened in another program, then it's possible that it didn't get closed correctly. This might be due to running into an error before hitting "close". To avoid this in the future use:
def log_message(logFilename, logMessageText):
with open(logFilename, "a") as file1:
file1.write(logMessageText + "\n")
The other problem you're having with the FileNotFoundError is because, well, the file doesn't exist. If you want to create it if it doesn't exist, your 'mode' string should be "a+", not just "a". So the final function name should read:
def log_message(logFilename, logMessageText):
with open(logFilename, "a+") as file1:
file1.write(logMessageText + "\n")
EDIT:
That bring said, you should avoid using double underscores, as it's true that Python uses these to denote special variables and functions. Best to keep clear of them for clarity's sake, if possible.

open() - Opening a file created via UI vs. via Console

I am starting Python and this is my first question on Stack Overflow.
I was doing some files handling recently and came up to an Error when trying to open a file to test it.
f = open("fi.txt", "r")
The problem is, I always run into an error like this:
Traceback (most recent call last):
File "C:\Users\USER\OneDrive\Documents\Python\Beginner\FileHandle2.py", line 9, in <module>
f = open("fi.txt", 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'fi.txt'
The path has been specified (via sys.path).
The file exist and it is placed in the same folder as my Python script (which is FileHandle2.py).
I do not understand what I am doing wrong here, if someone could give me some hint?
Moreover, when I do the following:
with open("fi2.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
The file "fi2.txt" is correctly created in my folder and I can call it without error when doing:
f = open("testy.txt", 'r')
Hence, I would like some hint on what is going on?
"fi.txt" was created with the UI (in Windows 10, right click > New > Text Document) while "fi2.txt" was created via the Python console.
Until now I know what to do, but I wanted to have explanation on this behavior.
Thank you peeps!
I found why, and it is really dumb.
When you create a Text file on Windows 10, you don't actually need to add the .txt extension, Windows 10 automatically add it. Also, the text files will show no extension as well.
I was quite used to type the extension myself tbh, so I never paid attention about the text files I was making.
Basically, on VS Code, the name of my file was:
fi.txt.txt

Python's readline() function seeming not to work?

for some reason the readline() function in my following code seems to print nothing.
fileName = input()
fileName += ".txt"
fileA = open(fileName, 'a+')
print("Opened", fileA.name)
line = fileA.readline()
print(line)
fileA.close()
I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:
Opened file!!
I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.
Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.
If you want to read from the top, you need to place fileA.seek(0) just before you call readline:
fileA.seek(0)
line = fileA.readline()
Doing so sets the pointer to the top of the file.
Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine. Those using a *nix system should not have this problem.

Opening '.txt' Files in Python

Answer Has Been Decided
The problem was not listing the entire file listing (i.e. DRIVE1\DRIVE2\...\fileName.txt).
Also, note that the backslashes must be turned into forwardslashes in order for
Python to read it (backslashes are outside of the unicode listing).
Thus, using: addy = 'C:/Users/Tanner/Desktop/Python/newfile.txt'
returns the desired results.
It's been a while since I have played with Python, and for my most recent class, we are required to make a BFS search that does a Word Puzzle that the Alice in Wonderland author created. I am just stating this, as the algorithm is the homework, which I have completed. In other words, my question does not apply to the answer to my homework question.
With that out of the way, I am in need of help on how to open, edit, read, create some form of text files in Python. My real problem is to place a list of words that I have inside of a .txt file, into a Dictionary dictionary. but I would much rather do this myself. Thus, I am left with how to do the said to text files.
NOTE:
I am running v3.3.
All documentation that I have found while searching how to solve this simple problem
is in regards to 2.7 or older.
I have tried to use:
>>> import sys from argv
>>> script, filename = argv
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
script, filename = argv
ValueError: need more than 1 value to unpack
I have also tried to use:
>>> f = open(newfile.txt, 'r')
But again, I get this error:
File "<pyshell#8>", line 1, in <module>
f = open (filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'newfile.txt'
However, I am positive that this file does exist. All of this being said, I am not sure if this is a directory problem, a problem understanding, or what... That is, anything would help!
First, if you want to retrieve a file name which is passed as the first argument to your script, use code like this:
import sys
if len(sys.argv) > 2:
filename = sys.argv[1]
else:
# set a default filename or print an error
Secondly, the error clearly indicates that the script can't find the file newfile.txt. So it is either not in the current directory, you don't have the permission to read it, etc...
To open a file for reading, use with command as follows
# This is python 3 code
with open('yourfile.txt', 'r') as f:
for line in f:
print(line)
with command used together with open command has already the raising exception process.

Python open() with minimal fluff variables

The intent is to look in a json file in the directory above the script and load up what it finds in that file. This is what I've got:
import os
import json
settings_file = '/home/me/foo/bar.txt'
root = os.path.dirname(os.path.dirname(os.path.abspath(settings_file))) # '/home/me'
target = os.path.join(root,'.extras.txt') # '/home/me/.extras.txt'
db_file= open(target)
databases = json.load(db_file) # works, returns object
databases2 = json.load(open(target)) # equivalent to above, also works
# try to condense code, lose pointless variables target and file
databases3 = json.load(open(os.path.join(root,'.extras.txt'))) # equivalent (I thought!) to above, doesn't work.
So... why doesn't the all-at-once, no holding variables version work? Oh, the error returned is (now in it's entirety):
$ ./json_test.py
Traceback (most recent call last):
File "./json_test.py", line 69, in <module>
databases = json.load(open(os.path.join(root,'/.extras.txt')))
IOError: [Errno 2] No such file or directory: '/.extras.txt'
And to satisfy S.Lott's well-intentioned advice... it doesn't matter what target is set to. The databases and databases2 populate correctly while databases3 does not. target exists, is readable and contains what json expects to see. I suspect there's something I don't understand about the nature of stringing commands together... I can make the code work, was just wondering why the concise (or complex?) version failed.
Code looks fine, make sure referenced files are in the appropriate places. Given your code that includes target/file variable assignment, full path to .extras.txt is
/home/me/.extras.txt
You need to do:
file = open(target, 'w')
because by default open will try to open the file in read mode (r) but you need to open it in w (write) mode if you want it to be created.
Also, I would not use the variable name file since it is also a type (<type 'file'>) in python.
You could add the write-mode flag to this line as well:
databases = json.load(open(os.path.join(root,'.extras.txt'), 'w'))
because from the limited information we have in the question it appears your /.extras file does not previously exist.
Final note, you are losing the handle to your open file in this line (since you are not storing it in your file variable):
databases = json.load(open(os.path.join(root,'.extras.txt')))
How do you intend to close the file when you're finished with it?
You could do this with a context manager (python >=2.6 or 2.5 if import with_statement used):
with open(os.path.join(root,'.extras.txt'), 'w') as f:
databases = json.load(f)
which will take care of closing the file for you.

Categories