如何使用 python 在 CSV 文件中添加新行
我有一个 csv 文件,其中包含时间 (hh:mm:ss) 和日期 (mm/dd/yyyy) 字段,以及另外 16 个字段。
一般情况下,时间字段每隔 30 英寸显示一次时间,但有时间隔可能会更长(分钟甚至小时)。
例如:
1/27/2011 12:10:00
1/27/2011 12:10:30
1/27/2011 12:11:00
1/27/2011 12:15:00
每当一行与下一行之间的间隙超过 30 英寸时,我需要添加新行(与它们之间的间隙一样多),并用间隙中第一行的值填充它们。
我想在不使用数据库环境的情况下完成此操作。是否可以? 如果是这样,你能给我一些好的建议吗?
I have a csv file that contains time (hh:mm:ss) and date (mm/dd/yyyy) fields, and sixteen more fields.
Generally the time field display time every 30'', but sometime the separation might be more (minutes or even hours).
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.
I would like to do it without working in a database environment. Is it possible?
If so, can you give me some good tips?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
缓冲最后两行,计算它们之间的时间差,并根据该时间差的条件测试结果写入输出。
Buffer the last two lines, calculate the time difference between them, and write output based upon the results of a conditional test on that time difference.
你检查过手册吗?
http://docs.python.org/library/csv.html
最后还有一些例子
我想到的第一个想法是迭代 csv 中的行并将它们一次一行复制到新的空白 csv,如果当前行和之前的行相距超过 30 英寸,然后在新的 csv 中添加必要次数之前的行。
Have you checked the manual?
http://docs.python.org/library/csv.html
there are also examples at the end
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.
我不确定我是否理解你的情况。如果文件是这样设置的:
那么您可以 将文件读入(或者可能只是最后两行)到您的程序中,可能作为行列表,检查两行之间的时间差是否> > 30",如果需要在数组中插入两行并重写整个文件。或者,您可以尝试就地编辑文件。
I'm not sure I understand your situation. If this is how the file is set up:
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.