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

2024-09-30 20:18:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我目前正在打开一个文件,阅读它,并试图打印它,最后把它放入一个新的文件

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()

事实上,一行字反复出现


Tags: 文件txtcloseoutputreadlinedefcontentsopen
1条回答
网友
1楼 · 发布于 2024-09-30 20:18:16

尝试:

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)

相关问题 更多 >