2017-02-08 1 views
-1

나는 다른 이름을 가진 새로운 섹션을 가지기 전에 해당 데이터가있는 섹션의 이름을 알려주는 화학 화합물 파일을 가지고있다. 'NAME'항목 ('NAME'부분 제외)을 읽고 각 이름 (여러 개가있는 경우)을 목록으로 읽은 다음 'FORMULA'섹션에 도달 할 때마다 중단하고 다음 항목으로 이동하려고합니다. 'NAME'섹션이지만 어떻게해야할지 모르겠다. 나는 초보 프로그래머이다. Compound List Screenshot enter image description here파일에서 파이썬으로 여러 줄의 데이터를 읽으려면 어떻게해야합니까?

여기 내 코드는 지금까지의 : 예를 들면 다음과 같습니다이다

li=[] #list of all names 
for line in inputFile: 
    if line[:5]=='ENTRY': 
     items = line.split() 
     cmNm = items[1] #compound Number 
    else line[:4]=='NAME': 
     items = line.split() 
     cmName = items[] 
     if line[:7]=='FORMULA': 
      break 
+0

한 점 :'else line [: 4] == ...'do'elif line [: 4] == ...' – jcfollower

+0

이 게시물의 답은 도움이 될 것입니다 ... http : // stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list – jcfollower

답변

0
with open('/path/to/file.txt', 'r') as inputFile: 
    for line in inputFile: 
     try: 
      # Skip lines until we find an entry 
      while len(line) < 5 or line[:5] != 'ENTRY': 
       line = inputFile.next() 
      # Setup for logging that entry 
      cmNm = line.split() 
      cmName = [] 
      # Append all name lines 
      while len(line) < 7 or line[:7] != 'FORMULA': 
       cmName.append(line) 
       line = inputFile.next() 
      # Process cmNm/cmName for current compound before moving on 
      print (str(cmNm) + " " + str(cmName)) 
     except StopIteration: 
      pass # Reached end of file 

cmNm는 ENTRY 라인의 분할 목록을 포함

cmName 함께 구성하는 라인의 목록이 포함되어 있습니다 이름.

원하는 처리 방법을 추가해야합니다. cmNm & cmName을 원하는대로 저장/포맷해야합니다. 나는 방금 그것이 그것으로서가는 것에 따라 그들을 인쇄하게했다.

마지막 유효 항목이 FORMULA 인 경우 StopIteration에서 pass을 안전하게 사용할 수 있습니다.

관련 문제