简体   繁体   中英

Why doesn't python standalone file manipulation function work?

I have a file test.py which works good. see code:

import os
import shutil
import re
for root, dirs, files in os.walk("../config/"):
    for file in files:
        print os.path.join(root, file)
        if file.endswith(".txt") and file.startswith("default_"):
            file_name = os.path.basename(os.path.join(root, file))
            file_name = re.sub(r'default_','',file_name)
            shutil.copy(os.path.join(root, file),os.path.join(root,file_name))

but when I wrapped the code into a function and put it in another file config.py. And I called the function in another file as config.copy_default_files(), it doesn't work. So I put a raw_input() in the end of the function to see if the function is executed, and it did print 'miao', but it didn't print out the list of files. And no file is generated or copied. I am so so confused.Can someone explain it to me please? Any help would be great appreciated. Let me know if you need more information on it. Manythanks!

import os
import shutil
import re
def copy_default_files(work_dir = "../config/"):
    for root, dirs, files in os.walk(work_dir):
        for file in files:
            print os.path.join(root, file)
            if file.endswith(".txt") and file.startswith("default_"):
                file_name = os.path.basename(os.path.join(root, file))
                file_name = re.sub(r'default_','',file_name)
                shutil.copy(os.path.join(root, file),os.path.join(root,file_name))
    raw_input('miao')
    return 0                 

Defining the function is not enough. You also need to call it:

copy_default_files()

or

config.copy_default_files()

(depending on whether you're running config.py as a script or importing it as a module).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM