【问题标题】:How to Write to a file and then read the file in Python如何写入文件,然后在 Python 中读取文件
【发布时间】:2020-07-15 10:36:03
【问题描述】:

我写了以下代码:

supported = open("Mails/mymails.txt",'w')
with open("emails.txt","r") as handle:
    for line in handle:
        if line.strip():
            list = line.split(":")
            email = list[0]
            domain = email.split("@")
            if domain[1] in blacklist:
                blacklisted = blacklisted+1
            if domain[1] in dictionary and domain[1] not in blacklist:
                valid=valid+1
                supported.write(domain[1])
            
    print(valid,blacklisted)
with open("Mails/mymails.txt",'r') as handle1:

    for line1 in handle1:
        print(line1)

我使用了附加模式,效果很好,但是当我使用多个文件时,我必须手动删除supported.txt文件以确保新文件行不会附加到旧文件行 任何帮助表示赞赏

【问题讨论】:

  • 目前还不清楚您的期望,如果使用.close() 是解决方案,那么您肯定应该在支持的文件上使用with 语句

标签: python python-3.x file


【解决方案1】:

我关闭了文件,它工作正常

like : supported.close() 在第一个 with 语句的末尾

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-16
    • 2015-08-06
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多