简体   繁体   English

如何使用python重写CSV中的一行?

[英]How to rewrite a line in a CSV using python?

I'm having some trouble with my code - I have a csv file and I have to save the first line in the csv as a list.我的代码有问题 - 我有一个 csv 文件,我必须将 csv 中的第一行保存为列表。 Then I have to clear the file and rewrite the line using the list.然后我必须清除文件并使用列表重写该行。 This is my code:这是我的代码:

import csv

f = open('PlateBook.csv','r')
reader = f.readlines()

for row in reader:
    outrow = list(row) 

    with open('PlateBook.csv', 'w', newline='') as fp:
        f.truncate
        a = csv.writer(fp, delimiter=',')
        data =  [outrow]

        a.writerows(data)

The trouble is, when I open the csv in Excel it's clearly wrong.问题是,当我在 Excel 中打开 csv 时,它显然是错误的。 Each character fills up a cell - I want the file to look exactly the same as when I written the file.每个字符填充一个单元格 - 我希望文件看起来与我编写文件时完全相同。

From the issue you describe, I guess that you don't want to do从你描述的问题来看,我猜你不想做

outrow = list(row) 

which simply creates a list of each charater, but more something like它只是创建了每个字符的列表,但更像是

outrow = row.split(',')

which create a list of the string separated by commas.它创建了一个由逗号分隔的字符串列表。

Or, even better , use a csv.reader , so it handle quotes and all little details of csv's.或者,更好的是,使用csv.reader ,这样它就可以处理引号和 csv 的所有小细节。

Here is an untested sample code of what you should do.这是您应该做什么的未经测试的示例代码。

import csv

with open('PlateBook.csv','rt') as input_file:
    reader = csv.reader( input_file )
    with open('PlateBook.temp.csv','wt') as output_file:
        writer = csv.DictWriter( output_file, fieldnames = csvreader.fieldnames )
        writer.writeheader()
        for row in reader:
            writer.writerow( row )

#So far we didnot touch the original file, so if the process
#fails, nothing is left in half-processed state.
import os
os.remove( 'PlateBook.csv' )
os.rename( 'PlateBook.temp.csv', 'PlateBook.csv' )

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

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