简体   繁体   中英

Anomaly in reading csv file column

I have the following file and code which works absolutely fine, but (see below) using the same methods, the second code snippet with the given file, throws up an error.

Working code

def test():
    with open('test.txt','r') as f:
        reader=csv.reader(f)
        for row in reader:
            print(row[0]) #this is column 1
            answer=input("Answer?>>")
            if answer==row[1]: #this is column 2
               print("Yes")
            else:
                print("No")

File contents

a,1
b,2
c,3

Correct working output

>>> test()
a
Answer?>>1
Yes
b
Answer?>>2
Yes
c
Answer?>>

However, the following code does not work:

def round():
    print("===Summary===")
    with open('eventinfo.txt','r',newline="") as f:
        reader=csv.reader(f)
        for row in reader:
            print(row[0])

File contents: (the extra line between records appears to have been created while writing to the file)

1,Techhamper,9,9,9,9,9,27

1,Moosecream,8,8,8,8,8,24

1,BizTech,6,6,6,6,6,18

1,Pigacheepot,1,1,1,1,1,3

2,Techhamper,1,1,1,1,1,3

2,Moosecream,2,2,2,2,2,6

Error:

print(row[0])
IndexError: list index out of range

The code that writes to this file is as follows:

with open("eventinfo.txt","a") as fo:
            writer=csv.writer(fo)
            writer.writerow([round,inventor,i1,i2,i3,i4,i5,totalscore])

For an answer, I would be delighted if:

  1. A solution/fix of the error in the code that reads from the file (how to strip the new line character most effectively)

  2. Additionally, what is the best way to add to or rewrite my 'write' code, to more efficiently create the file contents (to be like the first one that do not have the newline between each record) in the first place.

Thanks in advance

you can skip empty lines by checking the length of row :

for row in reader:
    if len(row) > 0:
        print(row[0])

I don't see anything in the writing code that would create blank lines, though, so I'm not sure how to fix that. Are you writing on the same operating system that you're reading on? If not, it could be due to differences in line ending conventions.

If the problem is with newlines, you might be able to fix the reader code by using newline=None (the default) instead of newline="" .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM