【问题标题】:How to read a file and print it, skipping certain lines in python如何读取文件并打印它,跳过python中的某些行
【发布时间】:2019-07-09 16:37:24
【问题描述】:

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

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

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

事实上,一行代码一遍又一遍地重复。

【问题讨论】:

  • 我看不出你是如何从中获得超过一行的输出的。您的函数读取第一个并检查它是否有冒号。它从不读取第二行,然后退出。
  • 是的,有办法让它一直找到那行,打印出来,然后重复到文件末尾?
  • 如果您在浏览器中搜索“Python 读取和写入文件”,您会找到比我们在此处管理的更能解释这一点的参考资料。

标签: python file loops


【解决方案1】:

试试:

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)

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    相关资源
    最近更新 更多