我想替换我的文本文件中的某一行,你是怎么做的?这是文本文件:
Description,Shoe Size,Quantity
Reebok 111,11,2
Reebok 111,12,4
Reebok 111,9,10
Reebok 1301,6,4
Reebok 1301,7,4
Reebok 1301,8,4
Reebok 1301,9,4
Reebok 1301,10,40
Reebok A55,8,7
Reebok A55,9,8
Reebok A55,10,41
Asics 193ABC,10,20
Asics 193ABC,12,4
Asics 193ABC,9,10
Asics 293BC,11,2
Asics 293BC,12,42
Asics 293BC,9,100
Nike N1,6,6
Nike N1,7,4
Nike N1,8,2
Nike N1,9,4
Nike N1,10,40
Mizuno P1039,4,12
Mizuno P1039,7,9
Mizuno P1039,8,2
Mizuno P1039,19,8
Mizuno P1039,20,4
Flag for copyright
这是我到目前为止所做的,但这只会在后面添加一条线
def modifyQty(dbfilename,modelname,size,newcount):
o=open(dbfilename,'a')
dbfilename=open(dbfilename,'r')#opendatafile for read and reassign
for line in dbfilename:
values=line.split(',')#split by comma
if values[0]==modelname and values[1]==size:
line=line.replace(values[2],newcount)
o.write(line+'\n')
o.close()
modifyQty('shoes.txt','Reebok 111','11','1')
我想将第一行 Reebok 111, 11, 2 编辑成 Reebok 111, 11, 1,寻找匹配的型号和尺寸,只更改数量。所以所需的输出是:
Reebok 111, 11, 1
谢谢
这是我所做的,它为 shoes.txt 的编辑版本创建了一个新的文本文件
def modifyQty(dbfilename,modelname,size,newcount):
o = open(dbfilename, 'r')
new_file = open('shoestextcopy.txt', 'w') #opens lol file
data = o.readlines()
for line in data:
values = line.split(',') # split by comma
if values[0] == modelname and values[1] == size:
line = line.replace(values[2], newcount)
new_file.write(line)
o.close()
new_file.close()
modifyQty('shoes.txt','Reebok 111','11','100000000 \n')
感谢所有的帮助