I have a txt file with data like this:
AL Autauga
AL Baldwin
AL Barbour
AL Bibb
def stateToCounties(filename):
"""
:param filename: text containing state name, tab, county name, enter button...
:return: { state name : [list of counties in that state] }
"""
filein = open(filename.txt, 'r')
lines = filein.readlines()
rawdata = []
states = {}
for line in lines:
line = line.strip('\n').split('\t')
rawdata += [line]
filein.close()
for part in rawdata:
if part[0] not in states.keys():
states[part[0]] = [part[1]]
else:
states[part[0]] += [part[1]]
return states
print(stateToCounties('uscounties.txt'))
I should be getting something like {'AL': [Autauga...]} as my output but instead got an error: AttributeError: 'str' object has no attribute 'txt'. If I use the line filein = open('filename.txt', 'r')
as opposed to filein = open(filename.txt, 'r')
then I get FileNotFoundError: [Errno 2] No such file or directory: 'filename.txt' as an error. How can I rectify this? The file is in the same folder as my .py file and I have read in files like this before so I don't understand what's wrong now.