简体   繁体   English

如何通过python将行附加到csv文件中,用逗号分隔新行和前一行

[英]How to append row into csv file through python with commas separating new row and previous

So..In this CSV file When I append a new row through python it comes directly in line with the previous row.所以..在这个 CSV 文件中,当我通过 python 添加新行时,它直接与前一行一致。 And the second time I open the code this error comes until I actually add spaces through the CSV file(in word pad) itself.第二次打开代码时,此错误出现,直到我实际通过 CSV 文件(在 Wordpad 中)本身添加空格。

Traceback (most recent call last):
File "C:\Users\mathew\Desktop\COMPUTER PROJECT - UNIVERSITY.py", line 300, in <module>
    NAME[row[0]]={'COUNTRY':row[1],'COURSE':row[2],'E-MAIL':row[3]}
IndexError: list index out of range

And This is the code snippet.这是代码片段。

p=[Name,c.capitalize(),co,e.lower()] 
with open ("list1.csv",'a') as r:
        w=csv.writer(r)
        w.writerow(p)
import csv
with open("list1.csv",'r') as fh:
       NAME={}
       s = csv.reader(fh)
       for row in s:
              NAME[row[0]]={'COUNTRY':row[1],'COURSE':row[2],'E-MAIL':row[3]}

I think that this is a really stupid mistake...but I am new to coding, so is there any part of code I am missing out.我认为这是一个非常愚蠢的错误......但我是编码新手,所以有没有我遗漏的代码部分。 Any help appreciated.任何帮助表示赞赏。

If you look at the documentation, when they open the file they put a newline argument.如果您查看文档,当他们打开文件时,他们会添加一个换行符参数。

    import csv
    with open('eggs.csv', newline='') as csvfile:
        spamreader = csv.reader(csvfile)
        for row in spamreader:
            print(', '.join(row))
    import csv
    with open('eggs.csv', 'w', newline='') as csvfile:
        spamwriter = csv.writer(csvfile)
        spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
        spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

For the part where you a reading the row from the file, you should check if each row contains the 4 items you need.对于从文件中读取行的部分,您应该检查每行是否包含您需要的 4 个项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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