首页 > 解决方案 > 读取文件时会出现一些错误吗?

问题描述

定义一个函数longest_lines,它接受一个文件名并返回该文件中该长度的所有行。

这是我的代码。

# define longest_lines
def longest_lines(file_name):
    content1 = open(file_name, "r").read()
    l1 = content1.strip().split("\n")
    max_number = max(map(int, map(len, l1)))
    def longest_char(char1):
        if len(char1) == int(max_number):
            return char1
    l2 = list(filter(longest_char, l1))
    return print(l2)

我创建了一个 words100.txt。但是当我运行一个文件时,它总是错误的。

>>> longest_lines(words100.txt)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'words100' is not defined
>>> longest_lines(words100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'words100' is not defined

在此处输入图像描述

标签: python

解决方案


你需要报价 -

longest_lines('words100.txt')

或双引号 -

longest_lines("words100.txt")

基本上,它应该像一个字符串。然后,您可以将其传递给函数。

此外,函数定义末尾的这一行 - return print(l2)应该只是return l2


推荐阅读