如何读取文件并打印,跳过python中的某些行

时间:2019-07-09 16:37:24

标签: python file loops

我想逐行读取文件,但忽略任何包含冒号(:)的文件。

我当前正在打开一个文件,读取它,并尝试打印它,然后最终将其放入新文件中。

def shoppinglist():
    infile = open('filename.txt')
    contents = infile.readline()
    output = open('outputfilename.txt', 'w')
    while ":" not in contents:
        contents = infile.readline()
    else:
        contentstr = contents.split()
        print(contentstr)
    output.write(contents)
    infile.close()
    output.close()

就这样,一遍又一遍地重复一行。

1 个答案:

答案 0 :(得分:0)

尝试:

def shoppinglist():
    contents = ""
    with open('filename.txt', 'r') as infile:
        for line in infile.readlines():
            if ":" not in line:
                contents += line

    with open('outputfilename.txt', 'w') as output_file:
        output_file.write(contents)