2014-11-02 1 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 

Это будет перейти к следующей итерации (линия) в случае строки не None, пустым или начинается с символа #.