简体   繁体   English

打印从函数返回的文件

[英]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 . 它是内置类型,例如intstr 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. fileopen_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.

相关问题 Python3:在另一个文件中打印函数返回的值 - Python3 : Print returned values from the function in another file 如何使用新 function 中一个 function 的返回值(列表)在用户所需的文件路径中将列表打印为 csv - How to Use the Returned Value (a list) from one function in a new function to print the list as a csv at the user's desired file path 如何使用python打印新行中函数返回的输出? - how to print the output returned from a function in new lines using python? 无法在模板中打印从视图功能返回的字典 - Not able to print the dictionary returned from view function in template 当我从Python将数据导出到csv时,该文件为空白。 当我使用打印功能查看数据时,将返回第一个字符串 - When I export data to a csv from Python, the file is blank. When I use Print function to see the data, the first string is returned 使用从函数返回的文件作为python中另一个函数的参数 - Using a file returned from a function as an argument for another function in python Python-函数未返回打印值 - Python - print values not being returned by function 如何在没有括号的情况下打印函数的返回元组 - How print the returned tuple of a function without parenthesis 在另一个文件中使用从无限循环 function 返回的变量 - Using variables returned from infinite loop function in another file 如何在机器人文件中使用python函数的多个返回值? - How to use multiple returned value from a python function in a robot file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM