我有一个5列的csv文件,我想在第6列添加数据.我拥有的数据是一个数组.
现在,我所拥有的代码只会在csv文件中已经存在的所有数据之后插入我想要的第6列数据.
比如我有:
wind, site, date, time, value
10, 01, 01-01-2013, 00:00, 5.1
89.6 ---> this is the value I want to add in a 6th column but it puts it after all the data from the csv file
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的代码:
csvfile = 'filename'
with open(csvfile, 'a') as output:
writer = csv.writer(output, lineterminator='\n')
for val in data:
writer.writerow([val])
Run Code Online (Sandbox Code Playgroud)
我认为使用'a'会将数据附加到一个新列中,但它只是将它放在('下')所有其他数据之后......我不知道该怎么办!
将数据写入文件的末尾,而不是写入每行的末尾.
而是创建一个新文件并将新值附加到每一行.
csvfile = 'filename'
with open(csvfile, 'r') as fin, open('new_'+csvfile, 'w') as fout:
reader = csv.reader(fin, newline='', lineterminator='\n')
writer = csv.writer(fout, newline='', lineterminator='\n')
if you_have_headers:
writer.writerow(next(reader) + [new_heading])
for row, val in zip(reader, data)
writer.writerow(row + [data])
Run Code Online (Sandbox Code Playgroud)
关于Python 2.x中,取出newline=''参数和从改变filemodes 'r'并'w'以'rb'和'wb',分别.
一旦您确定这是正常工作,您可以用新的文件替换原始文件:
import os
os.remove(csvfile) # not needed on unix
os.rename('new_'+csvfile, csvfile)
Run Code Online (Sandbox Code Playgroud)
小智 -1
打开文件的附加模式意味着将数据添加到文件的末尾。您需要做的是提供对您的文件写入的随机访问。你需要使用seek()方法
您可以在这里查看示例: http ://www.tutorialspoint.com/python/file_seek.htm
或者在这里阅读Python文档:https://docs.python.org/2.4/lib/bltin-file-objects.html这不是很有用
如果您想添加到列的末尾,您可能需要打开文件读取一行以找出其长度,然后查找到末尾。
| 归档时间: |
|
| 查看次数: |
20583 次 |
| 最近记录: |