简体   繁体   English

Python 2.0.7,将一些值逐行写入csv文件

[英]Python 2.0.7, write some values to csv file row by row

I have a lot of lists, each with twelve values: 我有很多列表,每个列表都有十二个值:

["0.0051", "-0.0351", ..., "0.0325"] [“ 0.0051”,“-0.0351”,...,“ 0.0325”]
["0.0065", "0.0014", ..., "0.0851"] . [“ 0.0065”,“ 0.0014”,...,“ 0.0851”]。 . . ["0.0151", "0.0512", ... , "0.00917"] [“ 0.0151”,“ 0.0512”,...,“ 0.00917”]

Each list has a id number that is like 2, 4, 7, 9... 每个列表的ID号都类似于2、4、7、9 ...

I want to write this list to a csv file row by row (if we see csv file by excel each row has 12 values and each row indicate the id_number) 我想将此列表逐行写到一个csv文件中(如果我们通过excel查看csv文件,则每行有12个值,每行表示id_number)

I just coded it like 我只是像这样编码

if existed_id != cur_id:
       cur_ id = existed_id
       value_list.append("/n")
       with open ('outcome.csv', 'w') as csvfile:
                 g = csv.writer(csvfile, delimiter = ',')
                 data = value_list
                 g.writerow(data)

When run, it is not fully written in my csv file. 运行时,它没有完全写在我的csv文件中。 What's going wrong? 怎么了

If your records are a list of lists od strings: 如果您的records是列表od字符串列表:

records = [["0.0051", "-0.0351", ..., "0.0325"],
           ["0.0065", "0.0014", ..., "0.0851"],
            . . .
           ["0.0151", "0.0512", ... , "0.00917"]`

then the following code will write a csv file with len(records) lines: 然后以下代码将用len(records)行写入一个csv文件:

with open('outcome.csv', 'w') as csvfile:
    g = csv.writer(csvfile, delimiter=',')
    for record in records:
         g.writerow(data)

The with open... line creates a new file (and overwrites a possibly previously existing file), so be sure you do not put it into a loop over records, because at the end only the last record would be saved into the file. with open...行会创建一个新文件(并覆盖以前可能存在的文件),因此请确保不要将其放入记录循环中,因为最后只会将最后一条记录保存到文件中。

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

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