how to skip over lines of a file if they are empty

2019-05-30 11:22发布

Program in python 3: This is my first program involving files. I need to ignore comment lines (start with #) and blank lines, and then split the lines so they are iterable, but I keep on getting and IndexError message that says string index out of range, and the program crashes on the blank line.

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条回答
成全新的幸福
2楼-- · 2019-05-30 12:00

Your problem comes from the fact that empty lines are not None, as you seem to assume. The following is a possible fix:

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
查看更多
我命由我不由天
3楼-- · 2019-05-30 12:06

Just use a continue statement in combination with if:

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

This will go to the next iteration (line) in case line is None, empty or starts with #.

查看更多
登录 后发表回答