修改具有特定条件的数据文件

时间:2013-07-15 18:14:51

标签: python text text-files

我有一个关于使用参考文件修改数据的问题。

参考文件(def.dat)包含三行和一列,如

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,我想仅在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

=========================== Code ================

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)

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

任何评论都表示赞赏。

1 个答案:

答案 0 :(得分:1)

我修改了你的代码。请参阅代码中的注释。

with open('def') as f1, open('abc') as f2, open('out.txt', 'w') as f3:
    in_atoms = False # state -> in_atoms (only 2 states)

    # read `def` file content into memory as set
    references = set(f1.read().split())

    # Removed a loop which iterate reference file.
    for line in f2:
        if line.startswith('Atoms'):
            in_atoms = True
        elif line.startswith('Velocities'):
            in_atoms = False
        elif in_atoms:
            values = line.split()
            # Check number match with one of the references.
            if values and values[0] in references:
                values[2] = '100'
                line = ' '.join(values) + '\n'
        f3.write(line)