0

参照ファイルを使用したデータの変更について質問があります。

参照ファイル (def.dat) には、次のような 3 つの行と 1 つの列が含まれています。

5
10
25

データ ファイル (abc.dat) には、次のような数字と単語が含まれています。

1 3 4
2 4 5

Atoms

1 4 5
1 5 6
5 8 4   <--- Here
3 5 10
3 5 9
6 2 6
6 8 9
10 6 7   <---- Here
8 5 4
8 8 6
45 5 9
45 10 54
25 10 1   <---- Here

Velocities

1 3 4
3 5 7

参照ファイルの値を比較した後、データ ファイルを変更したい。

たとえば、基準値が 5、10、および 25 の場合、データ ファイルの 3 列目の値を Atoms セクションのみで次のように変更したいと思います。

1 3 4
2 4 5

Atoms

1 4 5
1 5 6
5 8 100  <--- Here
3 5 10
3 5 9
6 2 6
6 8 9
10 6 100 <--- Here
8 5 4
8 8 6
45 5 9
45 10 54
25 10 100 <--- Here

Velocities

1 3 4
3 5 7

以下のコードを試してみましたが、基準値5だけみたいな変化でした。

1 3 4
2 4 5

Atoms

1 4 5
1 5 6
5 8 100  <--- only Here
3 5 10
3 5 9
6 2 6
6 8 9
10 6 7
8 5 4
8 8 6
45 5 9
45 10 54
25 10 1

Velocities

1 3 4
3 5 7

===========================コード ================

with open('def', 'r') as f1, open('abc', 'r') as f2, open('out.txt', 'w') as f3:
    state = 1

    for line1 in f1:
            sp1 = line1.split()
            for line2 in f2:
                    sp2 = line2.split()
                    line2 = " ".join(sp2) + '\n'

                    if line2 in ['\n', '\r\n']:
                            line2 = " ".join(sp2) + '\n'

                    elif line2 == 'Atoms\n':
                            state = 2

                    elif line2 == 'Velocities\n':
                            state = 3

                    if state == 1:
                            line2 = " ".join(sp2) + '\n'

                    elif state == 2:
                            if line2 == 'Atoms\n':
                                    line2 = " ".join(sp2) +'\n'

                            elif line2 in ['\n', '\r\n']:
                                    line2 = " ".join(sp2) +'\n'

                            else:
                                    if sp2[0] == sp1:
                                            sp2[2] = '10'
                                            line2 = " ".join(sp2) + '\n'

                    else:
                            line2 = " ".join(sp2) + '\n'

                    f3.write(line2)

================================================== =======

コメントをお待ちしております。

4

1 に答える 1