Skip to main content
 首页 » 编程设计

python之在 shell 中工作但不作为程序工作

2025年05月04日15pengyingh

我在 shell 中尝试了以下内容

infile = open("studentinfo.txt", "r") 
infile.read() 

它返回了文件中的文本,这正是我想要它做的。然而,当我编写并保存为程序时

def main(): 
    infile = open("studentinfo.txt", "r") 
    infile.read() 
main() 

它只是返回空行。

请您参考如下方法:

您的函数永远不会返回这些值,因此它们会再次被丢弃。

添加一个return语句:

def main(): 
    infile = open("studentinfo.txt", "r") 
    return infile.read() 

此外,在交互式解释器中,所有表达式结果都会自动回显,除非结果为None。在常规脚本中,您必须显式打印结果:

print(main())