0

My code takes the input and successfully writes to the 'data.csv' file, but whenever more than one number is entered as the initial input (e.g. '98765 12345') I get IndexError: list index out of range on the very last line.

Can anyone see where I'm going wrong?

x = raw_input('Enter numbers separated by a space: ')
new_FONs = [[int(i)] for i in x.split()]

with open('data.csv', 'a+') as f:
    writer = csv.writer(f)
    writer.writerows(new_FONs)

with open('data.csv', 'r') as f:
    all_FONs_str = [line.split() for line in f]
    all_FONs = [[int(FON[0])] for FON in all_FONs_str]

for FON in new_FONs:

    # Count the occurence of this number in the CSV file
    FON_count = all_FONs.count(FON)

    if FON_count == 1:
        print('once')

    elif FON_count == 2:
        print('twice')
  • What's the last element of `all_FONs_str ` ? – Juan C Jan 10 '20 at 15:08
  • https://stackoverflow.com/questions/3191528/csv-in-python-adding-an-extra-carriage-return-on-windows – Chris Jan 10 '20 at 15:11
  • @JuanC should just be a number as string? – bboooooyintheuk Jan 10 '20 at 15:11
  • @bboooooyintheuk it's not. You should either look at the csv file itself, or print(all_FONs_str) before the last line to see the problem. The link I provided in the comments will fix this issue. – Chris Jan 10 '20 at 15:14
  • @Chris I think it is because it's adding an extra line that's just blank in the csv file... and for some reason when I do a for loop it runs from last value to first, and this is encountering the blank. Is there a way to fix this? Will add for loop to original question too – bboooooyintheuk Jan 10 '20 at 15:20
  • @bboooooyintheuk did you try adding newline='' to your open calls as suggested in the link? – Chris Jan 10 '20 at 15:22

1 Answers1

0

Limiting the last loop to the penultimate element should do:

x = raw_input('Enter numbers separated by a space: ')
new_FONs = [[int(i)] for i in x.split()]

with open('data.csv', 'a+') as f:
    writer = csv.writer(f)
    writer.writerows(new_FONs)

with open('data.csv', 'r') as f:
    all_FONs_str = [line.split() for line in f]
    all_FONs = [[int(FON[0])] for FON in all_FONs_str[:-1]]
Juan C
  • 5,846
  • 2
  • 17
  • 51