簡體   English   中英

使用Python3讀取兩個文件並寫入一個文件

[英]Reading Two Files and Writing To One File Using Python3

我目前在Ubuntu 18.04上使用Python 3。 無論如何我都不是程序員,我也不要求進行代碼審查,但是,我遇到了一個似乎無法解決的問題。

我有1個名為content.txt文本文件,我正在從中讀取行。
我有1個名為standard.txt文本文件,我正在從中讀取行。
我有一個要寫入的名為outfile.txt文本文件。

content = open("content.txt", "r").readlines()
standard = open("standard.txt", "r").readlines()
outfile = "outfile.txt"
outfile_set = set()
with open(outfile, "w") as f:
    for line in content:
        if line not in standard:
            outfile_set.add(line)
    f.writelines(sorted(outfile_set))  

我不確定在哪里放置以下行。 我的for循環嵌套可能全部關閉:

f.write("\nNo New Content")  

任何使該工作有效的代碼示例將不勝感激。 謝謝。

我假設如果內容中的每一行都是標准的,則您想向文件寫入“無新內容”。 因此,您可以執行以下操作:

with open(outfile, "w") as f:
    for line in content:
        if line not in standard:
            outfile_set.add(line)
    if len(outfile_set) > 0:
        f.writelines(sorted(outfile_set))
    else:
        f.write("\nNo New Content") 

您的原始代碼快到了!

如果我很好理解,您希望添加outfile_set,如果此文件不為空,則添加字符串“ \\ nNo New Content”

更換線

f.writelines(sorted(outfile_set))

if any(outfile_set):
    f.writelines(sorted(outfile_set))
else:
    f.write("\nNo New Content")

您可以使用set / frozenset大大減少運行時間:

with open("content.txt", "r") as f:
    content = frozenset(f.readlines())  # only get distinct values from file
with open("standard.txt", "r") as f:
    standard = frozenset(f.readlines()) # only get distinct values from file

# only keep whats in content but not in standard
outfile_set = sorted(content-standard) # set difference, no loops or tests needed


with open ("outfile.txt","w") as outfile:
    if outfile_set:   
        outfile.writelines(sorted(outfile_set))
    else:   
        outfile.write("\nNo New Content")

你可以在這里讀更多關於它的內容:


演示:

# Create files
with open("content.txt", "w") as f:
    for n in map(str,range(1,10)):     # use range(1,10,2) for no changes
        f.writelines(n+"\n") 
with open("standard.txt", "w") as f:
    for n in map(str,range(1,10,2)): 
        f.writelines(n+"\n") 

# Process files:
with open("content.txt", "r") as f:
    content = set(f.readlines()) 
with open("standard.txt", "r") as f:
    standard = set(f.readlines())

# only keep whats in content but not in standard
outfile_set = sorted(content-standard)  

with open ("outfile.txt","w") as outfile:
    if outfile_set:
        outfile.writelines(sorted(outfile_set))
    else:
        outfile.write("\nNo New Content")

with open ("outfile.txt") as f:
    print(f.read())

輸出:

2
4
6
8

要么

No New Content

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM