python - 如何从 Python 中的 readlines 列表中选择一个项目?
问题描述
所以这就是我到目前为止的一个班级项目
import os
UserSelection = input("Select a txt file: ")
with open(UserSelection, 'r', encoding= "latin-1") as f:
lines= f.readlines()
print("These are your headers:", lines[0])
state = words()[6]
for i in range(1,len(lines)):
words=line.split
if(words()[6] == 'California'):
print(lines)
我有一个很大的人口普查表,我试图只保留 STATE(即第 6 个索引)为 CA 的行。我以为
words()[6]
会这样做,但事实并非如此。提前谢谢!
解决方案
欢迎来到 SO。在您发布的代码中,有几行不太清楚理解。
1)print("These are your headers:", lines[0])
没有正确缩进。
2)state = words()[6]
在此行之前没有定义单词。
3)for i in range(1,len(lines)):
在这一行中,您正在迭代行索引,而第一行可以替换为line in lines[1>]:
.
4)words=line.split
列表中的 split 方法在 python 中是可调用的,所以在使用该方法时应该使用 ()。
5)if(words()[6] == 'California'):
与拆分词不同的是,它是变量而不是方法,因此不应使用 () 调用它。
我理解的代码应该是代码的方式更像
import os
userSelection = input("Select a txt file: ")
with open(userSelection ,'r', encoding= "latin-1") as f:
lines= f.readlines()
print("These are your headers:", lines[0])
for line in lines[1:]:
words=line.split()
if words[6] == 'California':
print(lines)
推荐阅读
- python-2.7 - 自 2019 年 7 月 30 日起,独立的 App Engine SDK 已弃用。如何迁移 pycharm python2.7 应用程序
- javascript - 无法使用 html2canvas 拍摄谷歌地图快照
- vba - 从邮件合并中保存单个文档时出错
- javascript - React + 为第三方 url 的 CSS 和 Js 添加缓存清除
- node.js - GENERATE_SOURCEMAP=false 问题
- c# - 如何检查特定用户是否对远程机器上的特定文件夹具有读/写/任何权限?C#
- python - 在 python,BS4 上解析数据时得到“无”
- javascript - 在 Chrome 和 Edge 中工作但在 IE 中不工作的代码 - setimeout?
- php - 发送成功事件的电子邮件通知
- c++ - 如何从文件系统打印特定名称文件