0

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. 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

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

user2253899
  • 55
  • 1
  • 1
  • 6

1 Answers1

0

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')
Aamir Rind
  • 38,793
  • 23
  • 126
  • 164
  • so after writing into that new file, i need to have all my other data in there too – user2253899 Apr 07 '13 at 06:53
  • Yes you will have all of your data in new file. There are efficient methods also for reading and writing but depends on the requirement e.g. how big is the file. – Aamir Rind Apr 07 '13 at 06:55