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

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

我有这个文本文件,我想获取每一行末尾的值,对其进行处理,然后在不更改文本格式的情况下将其写回。所以基本上只需修改每行的最后一个值。

我目前的方法是使用 spacings/tabs 将行拆分为值列表,但我不知道如何将 spaces/tabs 放回原处.

有什么建议吗?

这也是我的模拟代码..

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

你真的不需要正则表达式。 标准字符串方法允许您 split a string at a specific character, and then 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+ 个制表符,然后匹配行尾的 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))