Python |如何在csv文件的每一行中添加字符串?

时间:2019-05-02 02:59:28

标签: python arrays list csv

我正在尝试向CSV的每一行添加“名称”字段。目前,我有一个数组,其中包含我要写入CSV的所有值。

我要添加的字段

diskimage_name = "name"

#Creating the Aarry 

arr_gpsbe = [r.split(",") for r in [r for r in text.split("{;}")]]


#arr_gps.be: values to be written

GPS BE:  [['171536396', '00000000000000000000000000000000', '2017-03-13T12/1 2/1 45/1', '51.5911', '-0.04806', '20.695', '0', ''], ['186839052', '00000000000000000000000000000000', '2017-03-13T12/1 2/1 45/1', '51.5411', '-0.0554806', '20.6495', '0', ''], ['261713932', '00000000000000000000000000000000', '2017-03-13T14/1 30/1 55/1', '51.547', '-0.06583', '19.3311', '0', ''], ['472133644', '00000000000000000000000000000000', '2018-02-13T12/1 2/1 47/1', '50.7414', '-1.8727', '3.5862', '0', ''], ['614559756', '00000000000000000000000000000000', '2018-02-13T12/1 3/1 0/1', '50.746', '-1.88712', '41.017', '0.32', ''], ['1249259520', 'f36baba228d0de8580380832d544d505', '2015-11-01T14/1 19/1 176/100', '51.508', '-0.096389', '26.0428', '0', ''], ['2296086528', '27f762ddb9443616987939a59ad7214d', '2016-08-22T11/1 26/1 10/1', '41.8994', '12.453', '28.0482', '0', ''], ['4045778956', '00000000000000000000000000000000', '2017-03-09T12/1 28/1 58/1', '51.411', '-0.03333', '18.3268', '0', ''], ['5446492172', '00000000000000000000000000000000', '2017-05-14T10/1 23/1 2644/100', '50.7371', '-1.289', '3.2384', '0.06631']]

#Csv Writer

 fieldnames = 'Disk Location', 'Hash', 'Date', 'Latitude', 'Longitude', 'Somethingelse', 'other'
        with open("C:\\ProgramData\\gps.csv", 'w', newline='', encoding="utf8") as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow(fieldnames)
            writer.writerows(arr_gpsbe)
            csvfile.close()

我正在尝试使数据看起来像这样:

Disk Name   Disk Location   Hash    Date    Latitude    Longitude   Somethingelse   other
Name    171536396   0   2017-03-13T12/1 2/1 45/1    51.5411 -0.0554806  20.6495 0
Name    186839052   0   2017-03-13T12/1 2/1 45/1    51.5411 -0.0554806  20.6495 0
Name    261713932   0   2017-03-13T14/1 30/1 55/1   51.5407 -0.0606583  19.3311 0
Name    472133644   0   2018-02-13T12/1 2/1 47/1    50.7414 -1.88727    39.5862 0
Name    614559756   0   2018-02-13T12/1 3/1 0/1 50.7416 -1.88712    41.0317 0.32

将“磁盘名称”字段添加到“ arr_gps”数组I.E的每个值是否容易

 arr_gpsbe = diskimage_name.join()[r.split(",") for r in [r for r in text.split("{;}")]]

还是使用csvwrtier将其添加到每一行更好?

writer.writerows(diskimage_name, arr_gpsbe)

1 个答案:

答案 0 :(得分:1)

代替:

writer.writerows(diskimage_name, arr_gpsbe)

使用:

writer.writerows([[diskimage_name, *row] for row in arr_gpsbe])

或者,或者:

for row in arr_gpsbe:
    writer.writerow([diskimage_name, *row])

如果要避免创建整个数据集的另一个副本。