在Python中写入多个文件

0 投票
2 回答
700 浏览
提问于 2025-04-17 05:27

我想在同一个文件夹里的很多*.py文件中写入“print 'hello'”。请问该怎么做?我在网上和StackOverflow上找了很多地方,但就是找不到方法。

就像伪代码那样,“打开某个文件夹里所有的*.py文件,然后写入'print 'hello'',最后关闭文件”。

抱歉,我是个新手,刚开始学习Python。

2 个回答

0

使用 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
4

你可以使用 glob 这个工具:

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

撰写回答