如果文件的行为空,如何跳过文件的行 [英] how to skip over lines of a file if they are empty

查看:278
本文介绍了如果文件的行为空,如何跳过文件的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python 3中编程:
这是我的第一个程序涉及文件。我需要忽略注释行(以#开头)和空白行,然后拆分这些行使它们是可迭代的,但我不断得到和IndexError消息,说字符串索引超出范围,程序崩溃在空白行。

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


推荐答案

您的问题来自空行不是 None ,因为你似乎假设。以下是可能的修正:

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

这篇关于如果文件的行为空,如何跳过文件的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆