读取在另一个函数中打开的文件的函数产生错误

时间:2017-10-18 00:22:13

标签: python function file

程序还有更多,但是现在这就是我遇到的麻烦;我想要两个不同的函数,open_file()打开一个.txt文件,然后是一个main()控制一切(除了open_file之外还有其它函数可以控制它)但我不能得到main()甚至打开并打印文件中的行。

def open_file():
    '''prompt for file name, open file, return file pointer'''
    filename = input("Input a file name: ")
    file=open(filename,'r')
    return file

def main():
    ## open the file
    open_file()
    file.readline()
    for line in file:
        print(line)
        #and then do other stuff with it
main()

当我运行main()时,它会提示输入文件名,但是当我输入它时,它会告诉我“name'file'没有定义。”我该如何纠正?

2 个答案:

答案 0 :(得分:2)

open_file()的返回值分配给main()中的变量:

def main():
    ## open the file
    file = open_file()
    ## ...

答案 1 :(得分:1)

您可以使用with打开文件,并在离开with时自动将其关闭。像这样:

Python3:

def main():
    filename = input("Input a file name: ")
    # Open the file, process it, and close it after processing.
    with open(filename) as f:
        process_file(f)

def process_file(fp_in):
    for line in fp_in:
        print(line, end="")
        #and then do other stuff with it

main()

Python2:

def main():
    filename = raw_input("Input a file name: ")
    # Open the file, process it, and close it after processing.
    with open(filename) as f:
        process_file(f)

def process_file(fp_in):
    for line in fp_in:
        print line,
        #and then do other stuff with it

main()