简体   繁体   English

修改文本文件行末尾的值 - 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

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

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

You may use a regex to match 1+ tabs and then 1+ digits at the end of the line with 您可以使用正则表达式匹配1 +标签,然后使用1+位数

r'(\t+)([0-9]+)$

Here is a regex demo . 这是一个正则表达式演示

See a Python demo that - for the demo purposes - just adds 30 to the value found with the regex: 查看一个Python演示 - 为了演示目的 - 只需在正则表达式中找到的值增加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))

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

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