So this is what i have so far for a class project
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)
i have a large census table and i'm trying to keep only lines where STATE(which is 6th index) is CA. i thought words()[6]
would do it but its not. thanks ahead!
Welcome to SO. In the code that you post there are few lines that not so clear to understand.
1) print("These are your headers:", lines[0])
is not indented properly.
2) state = words()[6]
the words is not defined before this line.
3) for i in range(1,len(lines)):
in this line you are iterating over lines indexes without the first line can be replaces with line in lines[1>]:
.
4) words=line.split
split method in lists is callable in python so you should use () when you use the method.
5) if(words()[6] == 'California'):
unlike split words is a variable not a method so it should not be called with ().
The way as I understand for you code that the code should be is more like
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)
It does work. Your error is indentation. Also, you have some other small errors.
. . .
for i in range(1,len(lines)):
words=line.split()
if (words[6] == 'California'):
print(lines)
.split()
is a function and should be called as one.
No need to unnecessarily indent either. Replacing the code snippet above with your old for
loop will do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.