[英]modifying a text file containing array with python
我想修改一個包含數字的文本文件。
例如,我有這個文本文件。
1 2 3 4 5
2 5 6 7 8
3 2 6 3 8
4 4 4 5 6
5 3 5 7 8
6 8 7 5 4
7 2 6 8 4
8 5 6 9 7
如果看到第二列,則為三個2。
然后,我想像這樣更改下一行中所有10的數字。
1 2 3 4 5
2 10 6 7 8
3 2 6 3 8
4 10 4 5 6
5 3 5 7 8
6 8 7 5 4
7 2 6 8 4
8 10 6 9 7
如果第二欄中有2,我想將下一個中的下一個數字更改為10
行。
任何意見,我深表感謝。
謝謝。
像這樣:
with open('abc') as f, open('out.txt','w') as f2:
seen = False #initialize `seen` to False
for line in f: #iterate over each line in f
spl = line.split() #split the line at whitespaces
if seen: #if seen is True then :
spl[1] = '10' #set spl[1] to '10'
seen = False #set seen to False
line = " ".join(spl) + '\n' #join the list using `str.join`
elif not seen and spl[1] == '2': #else if seen is False and spl[1] is '2', then
seen = True #set seen to True
f2.write(line) #write the line to file
輸出:
>>> print open('out.txt').read()
1 2 3 4 5
2 10 6 7 8
3 2 6 3 8
4 10 4 5 6
5 3 5 7 8
6 8 7 5 4
7 2 6 8 4
8 10 6 9 7
這個怎么樣:
with open('out.txt', 'w') as output:
with open('file.txt', 'rw') as f:
prev2 = False
for line in f:
l = line.split(' ')
if prev2:
l[1] = 10
prev2 = False
if l[1] == 2:
prev2 = True
output.write(' '.join(l))
我能想到的最簡單的方法是逐行讀取文件,並檢查第二個值是否== 2:
with open(file) as f:
line_old=f.readline()
matrix = line_old.split()
for line in f.readlines():
line_list=line.split()
if line_old.split()[1] == 2:
matrix.append(line_list[1]=10)
line_old=line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.