簡體   English   中英

用Python寫入多個文件

[英]Writing to Multiple Files in Python

我想將“ print'hello'”寫入同一目錄中的* .py文件中。 你是怎樣做的? 我已經在整個Web和SO上進行了搜索,但找不到方法。

就像在偽代碼中一樣,“在某個目錄中所有帶有* .py的文件,打開並寫入'print'hello',關閉文件”。

抱歉,我是n00b,我剛剛開始學習Python。

您可以使用glob:

import glob
for file in glob.glob("*.py"):
    with open(file, "a") as f:
        # f.write("print 'hello'")
        # etc.

使用glob.glob按模式選擇文件。

from glob import glob
from os.path import join

for f in glob(join(DIRECTORY, '*.pyc')):
    # open f and write the desired string to it

暫無
暫無

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

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