繁体   English   中英

如果文件行为空,如何跳过它们

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

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

您的问题来自一个事实,即您似乎假设空行不是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

只需将continue语句与if结合使用:

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

如果行为“无”,为空或以#开头,它将转到下一个迭代(行)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM