如何跳过文件中的空行
用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 个回答
1
只需要在代码中用一个continue
语句配合if条件就可以了:
if not line or line.startswith('#'):
continue
这样的话,如果这一行是None(没有内容)、空的,或者以#开头,就会跳到下一行继续处理。
4
你的问题出在你认为空行是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