使用Python csv模块覆盖csv文件中的特定列 [英] Overwrite a specific column in a csv file using Python csv module

查看:125
本文介绍了使用Python csv模块覆盖csv文件中的特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python csv模块读取csv文件,每一行都像这样:

I am using Python csv module to read a csv file with every line being like:

2013-04-16 7:11:01,186744,3,2,2,1.89E-03

然后我将row [0]转换为unix时间,但是我想用刚刚为csv文件的每一行找到的unix时间替换datetime

I then convert row[0] to unix time but then I want to replace the datetime with the unix time I just found for every row of my csv file

import pymongo
import datetime
import re
import csv
import calendar

X = []
OBD = []
Y = []

csv_in = open('FakeAPData.csv', 'rb')


for row in reader:
    date = datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
    datet = unicode(datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S'))
    datett = tuple(int(v) for v in re.findall("[0-9]+", datet))
    y = calendar.timegm(datett)
    Y.append(y)

所以我用unixtime值创建了列表Y,但是我该如何进行替换以便产生这样的输出:

So I create the list Y with the unixtime values but then how do I do the replacement so as to have an output like that:

1366097085,186744,3,2,2,1.89E-03

推荐答案

每个row只是一个list.您可以就地对其进行修改,也可以使用要替换的值创建一个新列表:

Each row is just a list. You can modify it in-place, or create a new list with the value you want substituted out:

row[0] = y # or row = [y] + row[1:], or ...

如果要将其写回文件,则需要使用csv.writer.例如:

If you want to write it back to a file, you need to use a csv.writer for that. For example:

os.rename('FakeAPData.csv', 'FakeAPData.csv.bak')

csv_in = open('FakeAPData.csv.bak', 'rb')
csv_out = open('FakeAPData.csv', 'wb')

writer = csv.writer(csv_out)

for row in csv.reader(csv_in):
    date = datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
    datet = unicode(datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S'))
    datett = tuple(int(v) for v in re.findall("[0-9]+", datet))
    y = calendar.timegm(datett)
    row[0] = y
    writer.writerow(row)


当然,您还需要close您的文件,并清理所有重复和未使用的代码.在此过程中,我会将日期转换代码分解为一个函数.并使用使操作变得容易的函数,而不是使操作变得困难和脆弱的函数.


Of course you'll also want to close your files, and clean up all the repeated and unused code. While we're at it, I'd factor out the date-transforming code into a function. And use functions that make it easy, instead of ones that make it difficult and fragile.

所以:

def transform_date(date):
    return calendar.gmtime(datetime.strptime(date, '%Y-%m-%d %H:%M:%S').timetuple())

def transform_row(row):
    return [transform_date(row[0])] + row[1:]

name = 'FakeAPData.csv'
bakname = name + '.bak'
os.rename(name, bakname)
with open(bakname, 'rb') as in csv_in, open(name, 'wb') as csv_out:
    writer = csv.writer(csv_out)
    writer.writerows(transform_row(row) for row in csv.reader(csv_in))

这篇关于使用Python csv模块覆盖csv文件中的特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆