替换文件中第行中的字符



我在文本文件中有这些不同的行和值

sample1:1
sample2:1
sample3:0
sample4:15
sample5:500

我希望":"后面的号码有时能更新我知道我可以用":"分割名称,得到一个有2个值的列表。

f = open("test.txt","r")
lines = f.readlines()
lineSplit = lines[0].split(":",1)
lineSplit[1] #this is the value I want to change

我不太确定如何用写函数

更新lineSplit[1]值

如果您试图修改相同的文件,则可以使用fileinput模块:

>>> strs = "sample4:15"

利用序列拆包的优势,将结果存储在拆分后的变量中。

>>> sample, value = strs.split(':')
>>> sample
'sample4'
>>> value
'15'

代码:

import fileinput
for line in fileinput.input(filename, inplace = True):
    sample, value = line.split(':')
    value = int(value)     #convert value to int for calculation purpose
    if some_condition: 
           # do some calculations on sample and value
           # modify sample, value if required 
    #now the write the data(either modified or still the old one) to back to file
    print "{}:{}".format(sample, value)

字符串是不可变的,也就是说,不能通过索引在其中分配新值。但是,您可以将整个文件拆分为一个行列表,并完全更改单个行(字符串)。这就是您在lineSplit[1]=A_NEW_INTEGER 中所做的

with open(filename, 'r') as f:
    lines = f.read().splitlines()
for i, line in enumerate(lines):
    if condition:
        lineSplit = line.split(':')
        lineSplit[1] = new_integer
        lines[i] = ':'.join(lineSplit)
with open(filename, 'w') as f:
    f.write('n'.join(lines)

也许是这样的(假设:之前的每个第一个元素确实是一个键):

from collections import OrderedDict
with open('fin') as fin:
    samples = OrderedDict(line.split(':', 1) for line in fin)
samples['sample3'] = 'something else'
with open('output') as fout:
    lines = (':'.join(el) + 'n' for el in samples.iteritems())
    fout.writelines(lines)

另一个选项是使用csv模块(在您的情况下,:是列分隔符)。

假设存在具有以下内容的test.txt文件:

sample1:1
sample2:1
sample3:0
sample4:15
sample5:500

您需要增加每个值。以下是您的操作方法:

import csv

# read the file
with open('test.txt', 'r') as f:
    reader = csv.reader(f, delimiter=":")
    lines = [line for line in reader]

# write the file
with open('test.txt', 'w') as f:
    writer = csv.writer(f, delimiter=":")
    for line in lines:
        # edit the data here
        # e.g. increment each value
        line[1] = int(line[1]) + 1
    writer.writerows(lines)

test.txt现在的内容是:

sample1:2
sample2:2
sample3:1
sample4:16
sample5:501

但是,无论如何,在您的情况下(编辑同一个文件)使用fileinput听起来更合乎逻辑。

希望能有所帮助。

最新更新