我想替換我的文本文件中的某一行,該怎麼做?這裏是文本文件:替換python文本文件中的行
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')
我想編輯的第一線,這是銳步111添加一行,11,2到銳步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')
感謝一個新的文本文件所有的幫助
有什麼不適合呢? – Antimony 2013-04-07 06:37:10
首先,您只能用逗號分割,而模型與空格分開。我先解決這個問題。爲什麼不先嚐試打印(值),看看有什麼實際內容。然後它更容易從那裏繼續.. – kramer65 2013-04-07 06:38:15
它只在文本文件的末尾添加一行:(哦,型號是銳步111不只是銳步 – user2253899 2013-04-07 06:38:43