读取在另一个函数中打开的文件的函数产生错误
问题描述:
程序比此更多,但现在这是我遇到的麻烦;我想要2个不同的函数,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(),它会提示输入文件名,但是当我进入它,它告诉我,“名‘文件’没有定义”。我该如何纠正?
答
您可以使用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()
您需要了解变量的作用域。通常,您应该将参数传递给函数,并返回要在该函数外部使用的数据。或者,您可以使用全局范围,但通常不建议这样做。 –