程序还有更多,但是现在这就是我遇到的麻烦;我想要两个不同的函数,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'没有定义。”我该如何纠正?
答案 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()