簡體   English   中英

為什么不正確的 output 被附加到我的 python 文件中?

[英]Why is the incorrect output being appended to my python file?

我有 python 文件試圖在此處修改其他 python 文件:

file = "PythonFile1.py"

with open(file, "r") as current_file:
    lines = current_file.readlines()
for line in lines:
    if line != 'sys.stdout = open("test.txt", "w")' or line != "sys.stdout.close()" or line != "import sys":
        del lines[lines.index(line)]
with open(file, "w") as current_file:
    for line in lines:
        current_file.write(line)

print(lines)

這是試圖修改的 python 文件:

import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()

當我運行第一個 python 文件時,我在另一個 python 文件中得到了這個結果。

sys.stdout = open("test.txt", "w")

我正在尋找文件的內容是:

import sys
sys.stdout = open("test.txt", "w")
sys.stdout.close()

我不確定為什么它沒有抓住我想留下的路線,有人可以幫助解決這個問題嗎?

with open(file, "w") as current_file:
    current_file.write('\n'.join(lines))

您不需要循環並編寫它們,只需加入行並直接編寫一次。 當您循環它時,每個循環都將替換文件中已有的內容,除非您使用 append 模式。 將這些線條連接在一起並直接編寫它們會更容易。


閱讀有關加入方法的更多信息

這是我要做的:

magic_lines = [
    "sys.stdout = open('test.txt', 'w')",
    "sys.stdout.close()",
    "import sys"
]

with open(infilepath, 'r') as infile:
    lines = infile.readlines()

with open(infilepath, 'w') as outfile:
    for line in lines:
        if line.strip() in magic_lines:
            outfile.write(line)

但在我看來,您可以完全刪除和鋪平文件:

from textwraps import dedent

with open(infilepath, 'w') as infile:
    infile.write(dedent("""\
        import sys
        sys.stdout = open("test.txt", "w")
        sys.stdout.close()
    """))

暫無
暫無

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

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