修改文本文件行末尾的值 - python

时间:2016-12-12 10:42:20

标签: python regex python-3.5 stringio

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

我有这个文本文件,我想在每行的末尾取值,对它做一些事情然后把它写回来而不改变文本的格式。所以基本上只需修改每一行的最后一个值。

我目前的做法是使用间距/标签将行分割成值列表,但我不知道如何将空格/标签重新放回原来的位置。

有什么建议吗?

这也是我的模拟代码..

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

2 个答案:

答案 0 :(得分:0)

你真的不需要正则表达式。 标准字符串方法允许您split特定字符处的字符串,然后再次join字符串。

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

答案 1 :(得分:0)

您可以使用正则表达式匹配1+个标签,然后使用

匹配行末尾的1+个数字
r'(\t+)([0-9]+)$

这是regex demo

请参阅Python demo - 出于演示目的,只需将30添加到使用正则表达式找到的值:

import re
def ammendedLineWithEditedValue(s): # TEST
    return int(s) + 30

lines = '''34512340 plain brackets      0.50    30
56756777    100mm bolts         0.20    0
90673412    L-shaped brackets   1.20    30'''
for line in lines.split("\n"):
    print(re.sub(r'(\t+)([0-9]+)$', lambda m: "{}{}".format(m.group(1), ammendedLineWithEditedValue(m.group(2))), line))