简体   繁体   English

逐行创建和附加 CSV

[英]Create and append CSV row by row

I would just like to create a csv file and at the same time add my data row by row with a for loop.我只想创建一个 csv 文件,同时使用 for 循环逐行添加我的数据。

for x in y:
    newRow = "\n%s,%s\n" % (sentence1, sentence2)
    with open('Mydata.csv', "a") as f:
        f.write(newRow)

After the above process, I tried to read the csv file but I can't separate the columns.经过上述过程后,我尝试读取 csv 文件,但无法将列分开。 It seems that there is only one column, maybe I did something wrong in the csv creation process?好像只有一栏,可能是我在csv创建过程中做错了什么?

colnames = ['A_sentence', 'B_sentence']
Mydata = pd.read_csv(Mydata, names=colnames, delimiter=";")
print(Mydata['A_sntence']) #output Nan

When you are writing the file, it looks like you are using commas as separators, but when reading the file you are using semicolons (probably just a typo).当您编写文件时,看起来您使用逗号作为分隔符,但在读取文件时您使用的是分号(可能只是一个错字)。 Change delimiter=";"更改delimiter=";" to delimiter="," and it should work. delimiter="," ,它应该可以工作。

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

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