python - 读取文件时会出现一些错误吗?
问题描述
定义一个函数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
解决方案
你需要报价 -
longest_lines('words100.txt')
或双引号 -
longest_lines("words100.txt")
基本上,它应该像一个字符串。然后,您可以将其传递给函数。
此外,函数定义末尾的这一行 - return print(l2)
应该只是return l2
推荐阅读
- dialogflow-es - 多项选择 - Dialogflow 中的预定义答案
- go - 如何从tendermint的GET tx响应中解码base64
- winapi - Win32 PKCS#7 Low Level Message Functions 使用特定内容
- java - java编译器api与springboot | 在tomcat下运行的问题
- android - apk 的调试版本被播放服务阻止
- android - React Native - 将后台蓝牙扫描任务安排为 Headless JS 服务
- reactjs - ReactJS onclick 按钮以表格格式显示 mongo 集合
- vb.net - 动态创建多个按钮并分配单击和双击命令
- c# - Process32FirstW 总是返回 false
- python - Scikit-learn 决策树提取特征节点