0

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.

3
  • 2
    Try writing out the actual pseudo-code. It will look remarkably similar to the real Python code. Commented Nov 1, 2011 at 21:28
  • 1
    Do you want to over-write the contents, or append to the file? Commented Nov 1, 2011 at 21:29
  • I want to append to the files Commented Nov 1, 2011 at 21:32

2 Answers 2

4

You can use glob:

import glob
for file in glob.glob("*.py"):
    with open(file, "a") as f:
        # f.write("print 'hello'")
        # etc.
Sign up to request clarification or add additional context in comments.

Comments

0

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

5 Comments

using this, I made it: from glob import glob from os.path import join for f in glob(join(DIRECTORY, '*.py')): # open f and write the desired string to it f = open("f", "wb") f.write( "Python is a great language.\nYeah its great!!\n"); f.close()
did I do that correctly? I've got a feeling that I flubbed up really really badly
just tried it out, and it says that "DIRECTORY" isn't defined
it's a compiled python program, isn't it?
*.pyc are binary files containing the compiled Python bytecode. Trying to write to them might not be a great idea. (Of course, you can always just trash them and let the compiler re-compile them from the corresponding source.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.