使用python修改包含数组的文本文件

时间:2013-07-01 17:36:34

标签: python file text

我想修改包含数字的文本文件。

例如,我有这个文本文件。

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

行。

任何评论,我深表感谢。

感谢。

3 个答案:

答案 0 :(得分:1)

这样的事情:

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

答案 1 :(得分:0)

这个怎么样:

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 :(得分:0)

我能想到的最简单的方法是逐行读取文件,并检查第二个值== 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