Sunday, 15 June 2014

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



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

program in python 3: first programme involving files. need ignore comment lines (start #) , blank lines, , split lines iterable, maintain on getting , indexerror message says string index out of range, , programme crashes on blank line.

import os.path def main(): endofprogram = false try: #ask user come in filenames input file (which #be animals.txt) , output file (any name entered user) inputfile = input("enter name of input file: ") ifile = open(inputfile, "r", encoding="utf-8") #if there not exception, start reading input file except ioerror: print("error opening file - end of program") endofprogram = true else: try: #if filename of output file exists inquire user #enter filename again. maintain asking until user enters #a name not exist in directory outputfile = input("enter name of output file: ") while os.path.isfile(outputfile): if true: outputfile = input("file exists. come in name again: ") ofile = open(outputfile, "w") #open input , output files. if exception occurs in opening files in #read or write mode grab , study exception , #exit programme except ioerror: print("error opening file - end of program") endofprogram = true if endofprogram == false: line in ifile: #process file , write result display , output file line = line.strip() if line[0] != "#" , line != none: info = line.split(",") print(data) ifile.close() ofile.close() main() # phone call main execute solution

your problem comes fact empty lines not none, seem assume. next possible fix:

for line in ifile: line = line.strip() if not line: # line blank go on if line.startswith("#"): # comment line go on info = line.split(',') # stuff info

python file python-3.x comments strip

No comments:

Post a Comment