字符串替换CSV中的多行

时间:2016-06-09 15:16:26

标签: python csv

以下是csv文件的摘录。第一列是产品编号,2是库存水平,3是目标水平,4是距目标的距离(目标减去库存水平。)

$VAR1 = [
    {   'total'   => '2',
        'results' => [
            {   'contact_type_name' => 'Primary Technical Contact',
                'street'            => undef,
                'state_id'          => undef,
                'state_name'        => undef,
                'last_name'         => 'Barb',
                'entities'          => [
                    {   'entity_name' => 'XXXXX',
                        'entity_id'   => 'XXXXX'
                    }
                ],
                'state_abbr_name' => undef,
                'city'            => undef,
                'country_id'      => undef,
                'latitude'        => undef,
                'contact_id'      => 'XXXXXX',
                'contact_type_id' => '1',
                'roles'           => [],
                'contact_methods' => [
                    {   'entity_name'              => undef,
                        'contact_method_value'     => 'XXXXXXX',
                        'contact_method_type_id'   => '4',
                        'contact_method_id'        => '24041',
                        'entity_id'                => undef,
                        'contact_method_type_name' => 'Cell Phone'
                    },
                    {   'entity_name'              => undef,
                        'contact_method_value'     => 'XXXXXX',
                        'contact_method_type_id'   => '2',
                        'contact_method_id'        => '24051',
                        'entity_id'                => undef,
                        'contact_method_type_name' => 'Office Phone'
                    },
                    {   'entity_name'              => undef,
                        'contact_method_value'     => 'example@example.com',
                        'contact_method_type_id'   => '1',
                        'contact_method_id'        => '24061',
                        'entity_id'                => undef,
                        'contact_method_type_name' => 'Email'
                    }
                ],
                'country_name'      => undef,
                'longitude'         => undef,
                'country_abbr_name' => undef,
                'full_name'         => 'NAME',
                'networks'          => [
                    {   'network_name' => 'NET',
                        'network_id'   => 'X'
                    }
                ],
                'timezone_id'   => undef,
                'zip'           => undef,
                'timezone_name' => undef,
                'title'         => 'MAC/Network Specialist',
                'first_name'    => 'Terri'
            },
            {   'contact_type_name' => 'Primary Technical Contact',
                'street'            => 'STREET',
                'state_id'          => undef,
                'state_name'        => undef,
                'last_name'         => 'NAME',
                'entities'          => [
                    {   'entity_name' => 'NAME',
                        'entity_id'   => '2679'
                    }
                ],
                'state_abbr_name' => undef,
                'city'            => 'CITY',
                'country_id'      => undef,
                'latitude'        => undef,
                'contact_id'      => '7896',
                'contact_type_id' => '1',
                'roles'           => [],
                'contact_methods' => [
                    {   'entity_name'              => undef,
                        'contact_method_value'     => 'example@example.com',
                        'contact_method_type_id'   => '1',
                        'contact_method_id'        => '16796',
                        'entity_id'                => undef,
                        'contact_method_type_name' => 'Email'
                    },
                    {   'entity_name'              => undef,
                        'contact_method_value'     => 'number',
                        'contact_method_type_id'   => '2',
                        'contact_method_id'        => '16797',
                        'entity_id'                => undef,
                        'contact_method_type_name' => 'Office Phone'
                    }
                ],
                'country_name'      => undef,
                'longitude'         => undef,
                'country_abbr_name' => undef,
                'full_name'         => 'NAME',
                'networks'          => [
                    {   'network_name' => 'net',
                        'network_id'   => '17'
                    }
                ],
                'timezone_id'   => undef,
                'zip'           => 'zip',
                'timezone_name' => undef,
                'title'         => 'Infrastructure Manager',
                'first_name'    => 'name'
            }
        ],
        'offset' => '0'
    },

    ...

当库存水平达到5或更低时,我希望在用户请求时从python更新库存水平。

我目前正在使用这段代码,我只是通过更新CSV中的一行来改编。虽然不行。第一行将作为34512340,0,95,95 12395675,3,95,92 56756777,70,95,25 90673412,2,95,93 写回文件,并删除文件的其余部分。

34512340,0,95,95

以下是我在CSV文件中更改一行并运行的代码:

    choice = input("\nTo update the stock levels of the above products, type 1. To cancel, enter anything else.")
if choice == '1':
    with open('stockcontrol.csv',newline='') as f:
        for line in f:
            data = line.split(",")
            productcode = int(data[0])
            target = int(data[2])
            stocklevel = int(data[1])
            if stocklevel <= 5:
                target = str(target)
                import sys
                import csv
                data=[]
                newval= target
                newtlevel = "0"
                f=open("stockcontrol.csv")
                reader=csv.DictReader(f,fieldnames=['code','level', 'target', 'distancefromtarget'])
                for line in reader:
                    line['level']= newval
                    line['distancefromtarget']= newtlevel
                    data.append('%s,%s,%s,%s'%(line['code'],line['level'],line['target'],line['distancefromtarget']))
                    f.close()
                    f=open("stockcontrol.csv","w")
                    f.write("\n".join(data))
                    f.close()
                    print("The stock levels were updated successfully")
else:
    print("Goodbye")

我可以更改什么才能使代码生效?我基本上希望程序循环遍历CSV文件的每一行,如果库存水平(第2列)等于或小于5,则将库存水平更新为第3列中的目标数量,然后设置数量第4列为零。

谢谢,

1 个答案:

答案 0 :(得分:1)

下面的代码读取每一行并检查第2列的值。如果它小于或等于5,则将column2的值更改为column3的值,将最后一列更改为0,否则将保留所有列不变。

import sys
import csv

data=[]
f=open("stockcontrol.csv")
reader=csv.DictReader(f,fieldnames=['code','level','target','distancefromtarget'])
for line in reader:
  if int(line['level']) <= 5:
    line['level']= line['target']
    line['distancefromtarget']= 0
  data.append("%s,%s,%s,%s"%(line['code'],line['level'],line['target'],line['distancefromtarget']))
f.close()


f=open("stockcontrol.csv","w")
f.write("\n".join(data))
f.close()

您的代码中出现问题:

您首先在不使用csv模块的情况下阅读该文件,并通过拆分该行来获取每列中的值。您再次使用DictReader模块的csv方法来阅读您已有的值。