cs中的字符串替换

2024-03-29 11:20:15 发布

您现在位置:Python中文网/ 问答频道 /正文

下面,我试图替换csv中的数据。代码可以工作,但它会替换文件中任何匹配的stocklevel

def updatestocklevel(quantity, stocklevel, code):
    newlevel = stocklevel - quantity
    stocklevel = str(stocklevel)
    newlevel = str(newlevel)
    s = open("stockcontrol.csv").read()
    s = s.replace (stocklevel ,newlevel) #be careful - will currently replace any number in the file matching stock level!
    f = open("stockcontrol.csv", 'w')
    f.write(s)
    f.close()

我的csv是这样的

34512340,1
12395675,2
56756777,1
90673412,2
12568673,3
22593672,5
65593691,4
98593217,2
98693214,2
98693399,5
11813651,85
98456390,8
98555567,3
98555550,45
98553655,2
96553657,1
91823656,2
99823658,2

在程序的其他地方,我有一个搜索代码的函数(8位) 如果code在csv行中,是否可以替换第二列中的数据?(数据[2])


Tags: 文件csv数据代码readdefcodeopen
3条回答

因为它是csv文件,我建议使用Python的csv模块。您将需要写入一个新文件,因为读取和写入同一个文件将变得不好。你可以在以后重新命名它。

本例使用StringIO(Python 2)将csv数据嵌入到代码中并将其视为文件。通常你会打开一个文件来获取输入。

已更新

import csv
# Python 2 and 3
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO


CSV = """\
34512340,1
12395675,2
56756777,1
90673412,2
12568673,3
22593672,5
65593691,4
98593217,2
98693214,2
98693399,5
11813651,85
98456390,8
98555567,3
98555550,45
98553655,2
96553657,1
91823656,2
99823658,2
"""


def replace(key, value):
    fr = StringIO(CSV)
    with open('out.csv', 'w') as fw:
        r = csv.reader(fr)
        w = csv.writer(fw)

        for row in r:
            if row[0] == key:
                row[1] = value
            w.writerow(row)

replace('99823658', 42)

当您调用s.replace (stocklevel ,newlevel)时,stocklevel的所有发生都将替换为newlevel的值。

string.replace(s, old, new[, maxreplace]): Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

source

正如您所建议的,您需要获得code,并使用它替换库存水平。

这是一个示例脚本,它以8位代码和新的stock level作为命令行参数并替换它:

import sys
import re
code = sys.argv[1]
newval= int(sys.argv[2]) 
f=open("stockcontrol.csv")
data=f.readlines()
print data
for i,line in enumerate(data):
  if re.search('%s,\d+'%code,line): # search for the line with 8-digit code
    data[i]  = '%s,%d\n'%(code,newval) # replace the stock value with new value in the same line
f.close()

f=open("in.csv","w")
f.write("".join(data))
print data
f.close()

使用Python的csv模块的另一个解决方案:

import sys
import csv

data=[]
code = sys.argv[1]
newval= int(sys.argv[2])
f=open("stockcontrol.csv")
reader=csv.DictReader(f,fieldnames=['code','level'])
for line in reader:
  if line['code'] == code:
    line['level']= newval
  data.append('%s,%s'%(line['code'],line['level']))
f.close()

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

警告:在尝试这些脚本覆盖输入文件时备份输入文件。

如果将脚本保存在名为test.py的文件中,则将其调用为:

python test.py 34512340 10

这将替换代码34512340到10的stockvalue。

为什么不使用好的旧正则表达式呢?

import re

code, new_value = '11813651', '885' # e.g, change 85 to 885 for code 11813651
print (re.sub('(^%s,).*'%code,'\g<1>'+new_value,open('stockcontrol.csv').read()))

相关问题 更多 >