1

I have this code where I am reading a csv file, using NamedTemporaryFile to change the contents of the csv file.

def update_localcsv():

    ping = ["Yes","No"]
    filename = 'file1.csv'
    tempfile = NamedTemporaryFile(mode= 'w',delete=False)

    with open(filename, 'rt') as csvFile, tempfile:
        reader = csv.reader(csvFile, delimiter=',', quotechar='"')
        writer = csv.writer(tempfile, delimiter=',', quotechar='"')

        for row in reader:

            print(row)
            row[0] = random.choice(ping)

            curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
            row[1] = str(curr_time)
            print('current time: '+str(curr_time))
            print("New ping status = " + str(row))
            writer.writerow(row)

    shutil.move(tempfile.name, filename)

When I run this code I can see print(row) printing ['Yes', '04:23 PM'] but then it throws IndexError: list assignment index out of range error at row[0] = random.choice(ping).

This is the current content in my csv file:

Yes,04:23 PM

Why is this error coming?

NOTE: When I do print(type(row)) I get <class 'list'>. I also see an empty row getting printed:

['Yes', '04:23 PM']
current time: 05:03 PM
New ping status = ['Yes', '05:03 PM']
[]
19
  • Re check if type(row) is a list. Commented Jul 6, 2017 at 20:51
  • @rakshith1124 when I do print(type(row)) I get <class 'list'> Commented Jul 6, 2017 at 20:54
  • 1
    create a new list and append the values instead Commented Jul 6, 2017 at 20:55
  • Do this instead: print('Row:', row). I bet you will see an extra empty row after the first line. Commented Jul 6, 2017 at 21:00
  • @DarnellMartin. Figure out what the problem is so you can avoid it before you move on to something better. Commented Jul 6, 2017 at 21:01

1 Answer 1

1

I was able to reproduce the error you are seeing by adding a newline at the end of my CSV file. I have taken the liberty of editing your question accordingly.

There are a few simple solutions. The most obvious would be to remove the trailing newline at the end of the file.

An more robust would be to skip any empty rows, or rows that do not have the two columns you require. You would still probably want to pass them through to the output writer, so you could do this (print statements omitted):

if len(row) == 2:
    row[0] = random.choice(ping)
    curr_time = datetime.datetime.time(datetime.datetime.now()).strftime('%I:%M %p')
    row[1] = str(curr_time)
writer.writerow(row)

If you want to remove empty lines, you can add a separate case for that:

if row:
    writer.writerow(row)

Since empty arrays are falsy, they will not be passed through.

Sign up to request clarification or add additional context in comments.

3 Comments

What if I want to remove the trailing empty newline? Since my file will always have one row that I posted above so I don't need the trailing empty newline. How can I skip it and thus avoid adding it to the updated new file?
@user2916886. Updated answer
I checked the updated answers just now and so I accepted it just now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.