本文介绍了Python附加到没有whiteline的csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我在python写一个游戏。在每轮游戏后(是的,游戏有多轮)我想把数据写入CSV文件。 这是我的代码: csv','a')as fp: for player in self.players:a = csv.writer(fp,delimiter =',') data = [[player.name,player.penalty(),player.score()]]; a.writerows(data); CSV文件中此代码的输出(两轮后)为:问题是每次脚本将数据附加到csv文件时,数据之间都有一条白线。而且我唯一想添加一条白线的时间是在回合之间。因此输出应如下所示: 我的新工作代码: code> with open('take5.csv','ab')as fp: for player in self.players:a = csv.writer(fp,delimiter =',') data = [[player.name,player.penalty(),player.score()]]; a.writerows(data); white_row = ['\\\']; a.writerows(white_row); 解决方案 Python 3: / p> with open('data.csv','a',newline ='')as fp: for player in self.players:a = csv.writer(fp,delimiter =','); data = [[player.name,player.penalty(),player.score()]]; a.writerows(data); 对于python 3,CSV模块中有更改,您可以阅读这里 Python 2.x: 只需将 open()改为binary open('data.csv ','ab') 您可以使用以下命令设置控制引用: csv.writer(fp,delimiter =',',quoting = csv.QUOTE_MINIMAL) 选项是: I'm writing a game in python. And after each round of the game (yes, the game has multiple rounds) I want to write the data to a CSV file.this is my code:with open('data.csv', 'a') as fp: for player in self.players: a = csv.writer(fp, delimiter=','); data = [[player.name, player.penalty(), player.score()]]; a.writerows(data);the output for this code (after two rounds) in the CSV file is:The problem is that every time the script appends data to the csv file, there is a white line between the data. And the only time I want to append a white line is between the rounds. So the output should look like this:Is there a way I can accomplish this?My new working code:with open('take5.csv', 'ab') as fp: for player in self.players: a = csv.writer(fp, delimiter=','); data = [[player.name, player.penalty(), player.score()]]; a.writerows(data); white_row = ['\n']; a.writerows(white_row); 解决方案 Python 3:with open('data.csv', 'a', newline='') as fp: for player in self.players: a = csv.writer(fp, delimiter=','); data = [[player.name, player.penalty(), player.score()]]; a.writerows(data);With python 3 there is change in the CSV module you can read herePython 2.x:Just change the open() to binary open('data.csv', 'ab')You can set control quoting using:csv.writer(fp, delimiter=',',quoting=csv.QUOTE_MINIMAL)As from docs your options are: 这篇关于Python附加到没有whiteline的csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-05 17:52