[英]Print a returned file from a function
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?
它是在open_file函数中定义的,并且是返回值...那么为什么不打印呢?
file
is the name of class object. file
是类对象的名称。 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. 您不需要
else
子句,因为您永远不会到达它。 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. try…except语句具有可选的else子句,该子句在存在时必须遵循所有except子句。 It is useful for code that must be executed if the try clause does not raise an exception.
对于try子句 未引发异常的 必须执行的代码而言,这很有用 。
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. 在文件对象上使用for循环进行迭代的行为逐行迭代文件。
First of all, don't use file
as a variable. 首先,不要将
file
用作变量。 It is a builtin type, like int
or str
. 它是内置类型,例如
int
或str
。 To print the file returned from open_file
, you need to use the file.readlines()
function: 要打印从
open_file
返回的文件,您需要使用file.readlines()
函数:
f = open_file()
for line in f.readlines():
print(line)
And an improvement for your open_file
function: 对
open_file
函数的改进:
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. file
是open_file
函数的局部变量。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.