def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
data = Source_obj.read()
I am having trouble opening this file while located in a sub-directory directly underneath my Python file... is there a better way to open files from ANY directory on my computer?
FileNotFoundError: [Errno 2] No such file or directory: 'WebSource\\EXAMPLE SOURCE.htm'
I can't read from the file because I get the following error:
C:\python34\python.exe G:\Robot\test.py
Process started >>>
Traceback (most recent call last):
File "G:\Robot\test.py", line 118, in <module>
functION()
File "G:\Robot\test.py", line 64, in functION
data = Source_obj.read()
AttributeError: 'str' object has no attribute 'read'
<<< Process finished. (Exit code 1)
================ READY ================
BTW: The file to be read is just a source file from an HTML Chrome webpage.
EDIT
I'm looking for more help with the path and wondering why I get the first mentioned Traceback regarding the path
os.path.relpath() returns a string, not an open file object. You'll need to open a file first; use the open() function:
def functION():
Source_obj = path.relpath(r"WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as fileobj:
data = fileobj.read()
with here treats the file object as a context manager; when the indented codeblock under the statement is exited (either because the code completed or an exception occurred), the file object will automatically be closed.
Your Source_obj is just a string, not a file.
def functION():
Source_obj = path.relpath("WebSource\EXAMPLE SOURCE.htm")
with open(Source_obj) as f:
data = f.read()
By open()-ing it you can read from the file. Using the with context manager, the file will be properly closed for you when you leave that block of code.
Related
What specific Python 3 syntax must be changed below in order to successfully print a trackback form a successfully running function into a file that is located at aValidFileNameAndPath?
We need this to work in normal running functions where there is NO exception.
The Python 3 code we are using is:
import traceback
traceback.print_stack(file=aValidFileNameAndPath)
The error thrown by the above code is:
File "C:\path\to\script\in\our\app\ourScriptName.py", line 69, in ourFunctionName
traceback.print_stack(file=aValidFileNameAndPath)
File "C:\Program Files\Python39\lib\traceback.py", line 190, in print_stack
print_list(extract_stack(f, limit=limit), file=file)
File "C:\Program Files\Python39\lib\traceback.py", line 25, in print_list
print(item, file=file, end="")
AttributeError: 'str' object has no attribute 'write'
The other postings we have found on Stack Overflow have to do with printing exceptions. We do NOT want to print an exception. Instead, we just want to print out the chain of functions that called a specific function during normal functioning of the app when there is no exception to be thrown.
You are getting this error because where you are using the file path the code wants a file object.
To make a file object, use open, e.g. myfile = open(aValidFileNameAndPath)
You will also want to set the file to writing mode, e.g. open(path, 'w')
Then you can pass myfile as a paremeter, e.g. traceback.print_stack(file=myfile)
Then make sure to close the file with close
Here is a full example:
import traceback
myfile = open(aValidFileNameAndPath, 'w') # note that this will delete anything that alredy exists in the file
traceback.print_stack(file=myfile)
myfile.close()
I'm trying to write a function that would use a loop to write multiple files, but it's not succeeding. Here are the code, and the result. The directory does exist; I was able to write, read, and append single files to it with no problem. This was done in the ordinary Python 3.9 interactive command line window on Windows 10.
def writepages(i):
for j in range(i):
name = f"0{j}0page.html"
file = open(f'C:\\Users\\cumminjm\\Documents\\{name}', 'r+')
file.close()
>>>
>>> writepages(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in writepages
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\cumminjm\\Documents\\000page.html'
Unlike "w" or "a", "r+" requires that the file already exist; it does not create the file if it does not already exist.
You should use a different file mode — such as:
w to open a (possibly new) file, and empty it if it exists.
a to open a (possibly new) file, but not empty it.
x to open a new file and fail with FileExistsError if it exists.
As #chepner pointed out, r+ opens an existing file for read and write.
According to this answer you can also use os.mknod("newfile.txt"), but it requires root privilege on macOS.
It's a bit off-topic, but you might like to know about pathlib, which gives you an OS-agnostic way to handle file paths, and using a context for the file opening, which is safer than open/close. Here's how I'd probably write that function:
import pathlib
def writepages(i):
"""Write i HTML pages."""
for j in range(i):
fname = pathlib.Path.home() / 'Documents' / f'0{j}0page.html'
with open(fname, 'x') as f:
f.write('')
return
I am trying to open a csv file using the csv module and then trying to read some data off of it using this code.
import csv
def file_open():
input_file=str(input('enter the input file to use'))
while True:
try:
with open(input_file,'r') as grades:
grades_reader=csv.reader(grades, delimiter=',')
break
except FileNotFoundError:
print('FileNotFoundError')
input_file=str(input('enter the input file to use'))
row_num=1
for row in grades_reader:
print('row',row_num,row)
row_num+=1
file_open()
and the file opening seems to be working until it gets to the part where it has to read the data and then it gives me an i/o error saying the file is closed. I am quite new to python and would appreciate any insight on what I did wrong.
also input_file is meant to allow the user to pick any file but I will only be using it to call one file called Grades.csv if that information will help
EDIT: traceback error message.
Traceback (most recent call last):
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 24, in <module>
file_open()
File "C:\Users\musta\OneDrive\Documents\computer assignment programs\program 4\Program4.py", line 18, in file_open
for row in grades_reader:
ValueError: I/O operation on closed file.
The file is closed because your break ends the loop, and the with body, therefore closing the file
You should keep that file reading code within the with indentation.
A csv.reader doesn't load the file into some in-memory list
I'm trying to read this .txt file through Python (3.6.5), using SublimeText3 (3.1.1). learning_python.txt is in the same directory as my python program. I tried to make it an absolute filepath but getting FileNotFoundError either way. I also tried running it through Terminal with the same outcome. Is the code wrong?
filename = 'learning_python.txt'
print("--- Reading in the entire file:")
with open(filename) as f:
contents = f.read()
print(contents)
Traceback is:
--- Reading in the entire file:
Traceback (most recent call last):
File "C:\Users\sulli\Documents\Coding\Python Crash Course\Ch_10_Files_Exceptions\about_python.py", line 6, in <module>
with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/sulli/Documents/Coding/Python Crash Course/Ch_10_Files_Exceptions/learning_python.txt'
Looks like the issue here was I had named learning_python.txt file with the .txt at the end just like it is in the code. When I deleted the .txt on the text file itself, it worked in Python to find learning_python.txt. Python must have seen it as learning_python.txt.txt.
I know you can open files, browsers, and URLs in the Python GUI. However, I don't know how to apply this to programs. For example, none of the below work. (The below are snippets from my growing chat bot program):
def browser():
print('OPENING FIREFOX...')
handle = webbroswer.get() # webbrowser is imported at the top of the file
handle.open('http://youtube.com')
handle.open_new_tab('http://google.com')
and
def file():
file = str(input('ENTER THE FILE\'S NAME AND EXTENSION:'))
action = open(file, 'r')
actionTwo = action.read()
print (actionTwo)
These errors occur, in respect to the above order, but in individual runs:
OPENING FIREFOX...
Traceback (most recent call last):
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
askForQuestions()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 64, in askForQuestions
browser()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 38, in browser
handle = webbroswer.get()
NameError: global name 'webbroswer' is not defined
>>>
ENTER THE FILE'S NAME AND EXTENSION:file.txt
Traceback (most recent call last):
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
askForQuestions()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 66, in askForQuestions
file()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 51, in file
action = open(file, 'r')
IOError: [Errno 2] No such file or directory: 'file.txt'
>>>
Am I handling this wrong, or can I just not use open() and webbrowser in a program?
You should read the errors and try to understand them - they are very helpful in this case - as they often are:
The first one says NameError: global name 'webbroswer' is not defined.
You can see here that webbrowser is spelled wrong in the code. It also tells you the line it finds the error (line 38)
The second one IOError: [Errno 2] No such file or directory: 'file.txt' tells you that you're trying to open a file that doesn't exist. This does not work because you specified
action = open(file, 'r')
which means that you're trying to read a file. Python does not allow reading from a file that does not exist.