Matt
Matt

Reputation: 5653

Writing to Multiple Files in Python

I want to write "print 'hello'" to a bunch of *.py files in the same directory. How do you do that? I've searched all over the Web and SO, and I can't find out how.

Like in pseudo-code, "all files with *.py in a certain directory, open and write 'print 'hello'', close file".

I'm sorry, I'm a n00b, I just started learning Python.

Upvotes: 0

Views: 713

Answers (2)

Nicolas
Nicolas

Reputation: 5678

You can use glob:

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

Upvotes: 4

Fred Foo
Fred Foo

Reputation: 363818

Use glob.glob to select files by pattern.

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

Upvotes: 0

Related Questions