2013-06-21 65 views
1

我有一個文本文件符合替換文件中的字符

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 

我不是很清楚如何更新與寫入功能

+1

你想寫回文件或...? –

+0

是的只是試圖用一個新號碼替換號碼真的 – user2117821

回答

0

可以使用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) 
+0

我可以用它來更新一些線,而不是所有的線嗎? – user2117821

+0

@ user2117821你可以添加一個簡單的'if'條件來檢查你是否要修改數據。 –

0

字符串是不可變的,這意味着lineSplit [1]值,你不能在其內部通過分配指標的新值。 但是,您可以將整個文件分割成一行行,並完全更改各個行(字符串)。這是你在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) 
0

或許真的是這樣的(假設:之前每個第一元素確實是一個關鍵):

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

另一種選擇是使用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聽起來更合乎邏輯的,你的情況來使用(編輯同一文件)。

希望有所幫助。