繁体   English   中英

如何使用 open() 定义 function

[英]How to define function using open()

我是 Python 的初学者,试图创建简单的代码来提取 txt 文件,并从中返回第一个单词。 我收到一个 NameError,告诉我“名称‘文件夹’未定义”。 代码和文件夹 > txtdocument 在同一目录中。

def first_word(file):

    text = open(file).read().strip().split()

    return print(text[0])


first_word(folder/txtdocument.txt)

对此的任何帮助将不胜感激!

您的代码几乎没有错误。 我已经调试了它们。 txt 文件的路径必须是字符串,但您没有为 txt 文件路径保留引号。 我们不需要返回打印语句,我们可以简单地打印它。

def first_word(file): 
    text = open(file).read().strip().split()
    print(text[0])

first_word("folder/txtdocument.txt")

路径需要作为字符串传递; 此外,您将返回对 print 方法的调用,而不是实际值。

def first_word(file):
    text = open(file).read().strip().split()
    return text[0]


print first_word("folder/txtdocument.txt")

应该是你要找的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM