字符串替换CSV中的多行 [英] String Replace for Multiple Lines In A CSV

查看:108
本文介绍了字符串替换CSV中的多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是csv文件中的代码段。第一列是产品编号,2是库存水平,3是目标水平,4是与目标(目标减库存水平)的距离。

Below is a snippet from a csv file. The first column is the product number, 2 is the stock level, 3 is the target level, and 4 is the distance from target (target minus stock level.)

34512340,0,95,95
12395675,3,95,92
56756777,70,95,25
90673412,2,95,93

当库存级别达到5或更低时,我想从python更新库存级别请求它。

When the stock level gets to 5 or below, I want to have the stock levels updated from python when a user requests it.

我目前正在使用这段代码,我只是更新了CSV中的一行。它不工作,但。第一行写回文件 34512340,0,95,95 ,文件的其余部分被删除。

I am currently using this piece of code which I have adapted from just updating one line in the CSV. It isn't working though. The first line is written back to the file as 34512340,0,95,95 and the rest of the file is deleted.

    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文件和工作原理:

Here is the code that I had changing one line in the CSV file and works:

with open('stockcontrol.csv',newline='') as f:
            for line in f:
                if code in line:
                    data = line.split(",")
                    target = (data[2])
    newlevel = stocklevel - quantity
    updatetarget = int(target) - int(newlevel)
    stocklevel = str(stocklevel)
    newlevel = str(newlevel)
    updatetarget = str(updatetarget)
    import sys
    import csv

    data=[]
    code = code
    newval= newlevel
    newtlevel = updatetarget
    f=open("stockcontrol.csv")
    reader=csv.DictReader(f,fieldnames=['code','level', 'target', 'distancefromtarget'])
    for line in reader:
      if line['code'] == code:
        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()

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

What can I change to make the code work? I basically want the program to loop through each line of the CSV file, and if the stock level (column 2) is equal to or less than 5, update the stock level to the target number in column 3, and then set the number in column 4 to zero.

感谢,

推荐答案

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

The below code reads each line and checks the value of column 2. If it is less than or equal to 5, the value of column2 is changed to value of column3 and last column is changed to 0 else all the columns are left unchanged.

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()

遇到您的代码中的问题:

Coming to issues in your code:

您首先读取该文件,而不使用 csv 模块,并通过拆分该行获取每列中的值。您正在使用 csv 模块的 DictReader 方法读取您已有的值。

You are first reading the file without using the csv module and getting the values in each column by splitting the line. You are again using the DictReader method of csv module to read the values you already had.

这篇关于字符串替换CSV中的多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆