2014-11-02 2 views
1

Python 3의 프로그램 : 이것은 파일과 관련된 첫 번째 프로그램입니다. 나는 주석 줄 (#로 시작하는)과 빈 줄을 무시하고 반복 가능하도록 줄을 나눌 필요가있다.하지만 나는 점점 계속해서 문자열 색인이 범위를 벗어나고 빈 줄에 프로그램이 충돌하는 IndexError 메시지를 계속 가져야한다.파일이 비어있는 경우 파일 줄을 건너 뛰는 방법

import os.path 

def main(): 

endofprogram = False 
try: 
    #ask user to enter filenames for input file (which would 
    #be animals.txt) and output file (any name entered by user) 
    inputfile = input("Enter name of input file: ") 

    ifile = open(inputfile, "r", encoding="utf-8") 
#If there is not exception, start reading the input file   
except IOError: 
    print("Error opening file - End of program") 
    endofprogram = True 

else: 
    try:  
     #if the filename of output file exists then ask user to 
     #enter filename again. Keep asking until the user enters 
     #a name that does not exist in the directory   
     outputfile = input("Enter name of output file: ") 
     while os.path.isfile(outputfile): 
      if True: 
       outputfile = input("File Exists. Enter name again: ")   
     ofile = open(outputfile, "w") 

     #Open input and output files. If exception occurs in opening files in 
     #read or write mode then catch and report exception and 
     #exit the program 
    except IOError: 
     print("Error opening file - End of program") 
     endofprogram = True    

if endofprogram == False: 
    for line in ifile: 
     #Process the file and write the result to display and to the output file 
     line = line.strip() 
     if line[0] != "#" and line != None: 
      data = line.split(",") 
      print(data)     
ifile.close() 
ofile.close() 
main() # Call the main to execute the solution 

답변

2

당신이 가정하는 것처럼 빈 줄은 None이 아닙니다. 가능한 픽스는 다음과 같습니다.

for line in ifile: 
    line = line.strip() 
    if not line: # line is blank 
     continue 
    if line.startswith("#"): # comment line 
     continue 
    data = line.split(',') 
    # do stuff with data 
0

그냥 경우와 조합에 continue 문을 사용 :이 경우 라인에서 다음 반복 (라인)로 이동합니다

if not line or line.startswith('#'): 
    continue 

없음 빈, 없거나 #로 시작합니다.

관련 문제