0

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

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

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

排。

任何意见,我深表感谢。

谢谢。

4

3 回答 3

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
于 2013-07-01T17:44:17.670 回答
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))
于 2013-07-01T17:43:41.560 回答
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
于 2013-07-01T17:49:00.400 回答