简体   繁体   English

替换python文本文件中的行

[英]Replace line in python text file

I want to replace a certain line in my text file, how do you do it? 我想替换文本文件中的特定行,该怎么办? Here is the text file: 这是文本文件:

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

This is what I've done so far but this only adds a line at the back 这是我到目前为止所做的,但这只会在后面添加一行

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

I want to edit the first line, which is Reebok 111, 11, 2 into Reebok 111, 11, 1, looking for the matching model and size and changing only the quantity. 我想将第一行Reebok 111、11、2编辑为Reebok 111、11、1,以寻找匹配的型号和尺寸,并仅更改数量。 so the desired output is: 所以所需的输出是:

Reebok 111, 11, 1

Thanks 谢谢


Here is what I did and it creates a new text file for the edited version of the shoes.txt 这是我所做的,它为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')

Thanks for all the help 谢谢你的帮助

I'll suggest open a new file for writing: 我建议打开一个新文件进行写入:

def modifyQty(dbfilename,modelname,size,newcount):
    o = open(dbfilename, 'r')
    new_file = open('abc.txt', 'w')
    data = o.readlines()
    for line in data:
        values = line.split().split(',') # split by comma
        if values[0] == modelname and values[1] == size:
            line = line.replace(values[2], newcount)
        new_file.write(line + '\n')
    o.close()
    new_file.close()

modifyQty('shoes.txt','Reebok 111','11','1')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM