0

I have a list in a file looks like this:

Adair, KY
Jackson, MS
Chicago, IL
ALASKA

I need to split the strings and re-write them to a new file like this:

KY:Adair
MS:Jackson
IL:Chicago

leaving out the state only names.

this is what I have so far:

county_file = open("c:\\Python 3.8.3\\us-counties.2.txt", "r")
lines = county_file.readlines()
state_file = open("c:\\Python 3.8.3\\Ronnie.Vincent.County.Seats.manipulated.txt", "w")

for aline in lines:
    values = aline.split()
    print(values[1],':', values[0])
      
state_file.close()    
county_file.close()

I keep getting a 'list index out of range' error because the State only names do not have a values[1]. I can not figure out how to leave the state only names out. Any help would be greatly appreciated, I'm stuck.

TheOneMusic
  • 1,776
  • 3
  • 15
  • 39

1 Answers1

1

If you want to leave out the State only lines completly the simplest solution would be:

for aline in lines:
  try: 
    values = aline.split() 
    print(values[1],':', values[0])
  except IndexError:
    print('skipping line', aline)
Lukr
  • 659
  • 3
  • 14
  • Sorry I'm completely green when it comes to programming. It gives me IndexOutOfRangeException not defined. Do I need to create a variable for it? – user13958943 Jul 19 '20 at 16:29
  • that was my bad, should be an IndexError not IndexOutOfRangeException. Fixed it in my answer. – Lukr Jul 19 '20 at 16:30