简体   繁体   English

如何使用python在CSV文件中添加新行

[英]how add new line in CSV file using python

I have a csv file that contains time (hh:mm:ss) and date (mm/dd/yyyy) fields, and sixteen more fields. 我有一个csv文件,其中包含时间(hh:mm:ss)和日期(mm / dd / yyyy)字段,以及另外16个字段。

Generally the time field display time every 30'', but sometime the separation might be more (minutes or even hours). 通常,时间字段每30英寸显示一次时间,但有时间隔可能会更长(几分钟甚至几小时)。

For instance: 例如:

1/27/2011 12:10:00 
1/27/2011 12:10:30 
1/27/2011 12:11:00 
1/27/2011 12:15:00

I need to add new lines (as many as the gap between them) every time the gap between a line and the next is more the 30'', and fill them out with the values from the first line in the gap. 每当一行与下一行之间的间隙大于30英寸时,我需要添加新行(与它们之间的间隙一样多),并用间隙中第一行的值填充它们。

I would like to do it without working in a database environment. 我不想在数据库环境中工作。 Is it possible? 可能吗? If so, can you give me some good tips? 如果是这样,您能给我一些好建议吗?

缓冲最后两行,计算它们之间的时间差,然后根据对该时间差进行条件测试的结果写入输出。

Have you checked the manual? 你看过手册了吗? http://docs.python.org/library/csv.html there are also examples at the end http://docs.python.org/library/csv.html最后还有示例

The first idea that comes to my mind is iterating over the rows in the csv and copying them to a new blank csv one row at a time, if current row and row before are more than 30" apart, then add row before the necessary amount of times to the new csv. 我想到的第一个想法是遍历csv中的行,一次将它们复制到一个新的空白csv中,如果当前行与之前的行相距超过30英寸,则在必要的行数之前添加行时代到新的csv。

I'm not sure I understand your situation. 我不确定我是否了解您的情况。 If this is how the file is set up: 如果这样设置文件:

1/27/2011 12:10:00 xxx xxx xxx xx...
1/27/2011 12:10:30 xxx xxx xxx xx...
1/27/2011 12:10:00 xxx xxx xxx xx...
1/27/2011 12:15:00 xxx xxx xxx xx...

then you can read the file (or maybe just the last two lines) into your program, maybe as a list of lines, check to see if the time difference between the two lines is > 30", and if need be insert two lines into the array and rewrite the whole file. Or, instead of that, you could try to edit the file in place. 然后您可以将文件 (或者可能只是最后两行)读入程序(也许以行列表的形式),检查两行之间的时间差是否大于30“,并且是否需要将两行插入数组并重写整个文件;或者,您可以尝试在适当位置编辑该文件,而不是改写整个文件。

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

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