2013-07-15 2 views
0

참조 파일을 사용하여 데이터를 수정하는 방법에 대한 질문이 있습니다.특정 조건의 데이터 파일을 수정 중

참조 파일 (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 

I는 변경하고자 같이 숫자와 단어가 포함 참조 파일 값을 비교 한 후 데이터 파일

기준값은 5, 10 및 25을 실시 예를 들어, 난에만 같은 원자 섹션 데이터 파일 번째 열에있는 값을 변경하고자

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) 

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

의견을 보내 주시면 감사하겠습니다.

답변

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) 
+0

귀중한 의견과 코드를 수정 해 주셔서 감사합니다. 그것은 많은 도움이됩니다. 그러나 두 번째 "참고 문헌"입니다. 마지막 if 문에서 실수? –

+0

@ChangWoonJang, 네, 실수였습니다. 나는 그것을 고쳤다. – falsetru