Search code examples
pythonregexpython-3.5stringio

Amend value at the end of a line on a text file - python


34512340    plain brackets      0.50    30
56756777    100mm bolts         0.20    0
90673412    L-shaped brackets   1.20    30

I have this text file and I want to take the value on the end of each line, do something to it and then write it back without changing the formatting of the text. So basically just amend the last value on each line.

My current approach is to split the line up into a list of values using the spacings/tabs, but I don't know how I can put the spaces/tabs back in after as it was before.

Any suggestions?

Also here's my mock up code..

import re
import fileinput
with open('stock.txt', 'r') as stock:
    stockList = stock.readlines()

print(stockList[0])
print(re.split(r'\t+', stockList[0].rstrip('\t').rstrip('\n')))
with fileinput.FileInput('test.txt', inplace=True) as file:
     for line in file:
         print(line.replace(stockList[0], ammendedLineWithEditedValue), end='')

Solution

  • You don't really need regular expressions for that. The standard string methods allow you to split a string at a specific character, and then join the string back again.

    with open('stock.txt', 'r') as stock, \
         open('test.txt', 'w') as test:
      for line in stock:
        tokens = line.split('\t')
    
        # Edit last token in line
        tokens[-1] = str(int(tokens[-1]) + 5)
    
        result = '\t'.join(tokens)
        test.write(result + '\n')