I just want to print a file that is returned from a separate function:
def open_file():
while True:
try:
filename = input("Input a file name: ")
file=open(filename,'r')
return file
except FileNotFoundError:
print("Error: Enter a valid file.")
continue
else:
break
open_file()
for line in file:
print(line)
It's prompting for the file, and gives the error and re-promts when an invalid file is entered, but when a valid file is entered, it says that "file" is not defined. It's defined in the open_file function though, and is the returned value... So why doesn't it print?
file
is the name of class object. You should use something else; The problem in your code is that you don't save the return code from your function.
def open_file():
while True:
filename = input("Input a file name: ")
try:
f = open(filename,'r')
return f
except FileNotFoundError:
print("Error: Enter a valid file.")
continue
f = open_file()
for line in f:
print(line)
You don't need to else
clause, because you never reach it. You return from the function if there is no exception, and if there is - the else clause doesn't get executed anyway.
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception.
You can do the same with more elegant way;
for line in open_file():
print line
The behavior of iterating with a for loop on a file object iterates the file line-by-line.
First of all, don't use file
as a variable. It is a builtin type, like int
or str
. To print the file returned from open_file
, you need to use the file.readlines()
function:
f = open_file()
for line in f.readlines():
print(line)
And an improvement for your open_file
function:
def open_file():
while True:
try:
return open(raw_input("Enter a file name: "), 'r')
except FileNotFoundError:
print("Error: Enter a valid file name.")
file
is a local variable of your open_file
function. It is therefore not available outside of the function. You should assign asign the return value:
def open_file():
while True:
try:
# ...
return file
except FileNotFoundError:
# ...
# no break needed; the return statement ends the function
file = open_file()
for line in file:
print(line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.