开发者

csv python questions

i am opening a csv file like this:

import csv
reader = csv.reader(open("book1.csv", "rb"))
for row in reader:
   开发者_开发知识库 print row

how can i replace the value in column 3 with its log and then save the result into a new csv?


Like this?

>>> input = "1,2,3\n4,5,6\n7,8,9".splitlines()
>>> reader=csv.reader(input)
>>> for row in reader:
...     row[2] = log(float(row[2]))
...     print ','.join(map(str,row))
...
1,2,1.09861228867
4,5,1.79175946923
7,8,2.19722457734


These links might help:

http://docs.python.org/library/csv.html#csv.writer

http://docs.python.org/tutorial/datastructures.html?highlight=array

Each row being returned by reader is an array. Arrays in Python are 0 based (So to access the third entry in a row, you would use my_array[2])

That should help you on your way.


You should use the context manager WITH statement for files - cleaner, less code, obviates file.close() statements.

e.g.

import csv
import math
with open('book1.csv', 'rb') as f1,open('book2.csv', 'wb') as f2:
    reader = csv.reader(f1)
    writer = csv.writer(f2)
    for row in reader:
        row[2] = str(math.log(float(row[2])))
        writer.writerow(row)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜