Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python在数据行中格式化/插入逗号_Python_Sql - Fatal编程技术网

使用python在数据行中格式化/插入逗号

使用python在数据行中格式化/插入逗号,python,sql,Python,Sql,我有一个定期附加的CSV文件,其中包含两种类型的类似数据。我无法控制数据是如何进入CSV的,但我想执行一个python脚本来格式化CSV,以便将其接收到数据库中。以下是我想做的: 传入的原始数据如下所示: record, date & time, sensor, height, status record, date & time, sensor, height, weight, status 这样做的想法是,如果没有体重或类似的东西,只需迭代地获取这些数据,在身高后添加一个

我有一个定期附加的CSV文件,其中包含两种类型的类似数据。我无法控制数据是如何进入CSV的,但我想执行一个python脚本来格式化CSV,以便将其接收到数据库中。以下是我想做的:

传入的原始数据如下所示:

record, date & time, sensor, height, status

record, date & time, sensor, height, weight, status
这样做的想法是,如果没有体重或类似的东西,只需迭代地获取这些数据,在身高后添加一个逗号。基本上模拟空白字段,以便数据基本上如下所示:

record, date & time, sensor, height, **weight,**status (updated after python script if/then)

record, date & time, sensor, height, weight, status

希望这是有意义的-基本上是添加一个字段,每次文件更新时我都会运行脚本

你关心csv转义和引号吗?
import csv
import os
with open('yourfile.csv') as f_in, open('yourfile.csv.temp') as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    for row in reader:
        if len(row) == 5:
            row.insert(4, '')
        writer.writerow(row)
os.rename('yourfile.csv.temp', 'yourfile.csv')