简体   繁体   English

为什么python独立文件操作功能不起作用?

[英]Why doesn't python standalone file manipulation function work?

I have a file test.py which works good. 我有一个文件test.py很好用。 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. 但是,当我将代码包装到一个函数中并将其放入另一个文件config.py中时。 And I called the function in another file as config.copy_default_files(), it doesn't work. 我在另一个文件中将该函数称为config.copy_default_files(),它不起作用。 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. 因此,我在函数的末尾放置了raw_input(),以查看该函数是否已执行,并且确实打印了“ miao”,但未打印出文件列表。 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). (取决于您是将config.py作为脚本运行还是作为模块导入)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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