在标题和空行之间打印文件中的行

时间:2013-10-22 20:05:15

标签: python file

我有一个具有以下结构的文件:header - data - blank lines - header ...我正在尝试在标题和第一个空白行之间打印数据文件的行。我使用的那段代码似乎不起作用;你有什么建议吗?

for j in range(0, number_of_angles, 1):
    start_line = omega_line_number[j]+5 #start line is the line number after the header
    print start_line
    for line in range(start_line,num_lines,1): #num_lines is the total number of lines
        stripped = line.strip()
    if not stripped:
        break
    print line

2 个答案:

答案 0 :(得分:0)

line将是integer,并且没有方法,strip()

答案 1 :(得分:0)

我写了一个快速程序,该程序适用于我为此制作的文本文件。基本上,文本文件包含10行包含单词“header”和20行包含单词“body”。在那之后,我有10个空行并重复前30行。这是仅打印正文的代码。

if __name__ == '__main__':                                                       
    # Open the file for reading.                                                 
    rd_file_name = "../txt/q1.txt"                                               
    rd_file = open(rd_file_name, 'r')                                            

    # Read through the header                                                    
    for line in rd_file.readlines():                                             
        # Decide what to do based on the content in the line.                    
        if "header" in line.lower():                                             
            # Don't print the header                                             
            pass                                                                 
        elif line.strip() == "":                                                 
            # Quit if you see a blank line                                       
            break                                                                
        else:                                                                    
            # We print the body.  Lines end with a carriage return, so we don't  
            # add another one.                                                   
            print line,                                                          

    # Clean up                                                                   
    rd_file.close()