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

這會去的情況下,線下一次迭代(行)是無,空或#開始。

相關問題