繁体   English   中英

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

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

我有一个文件test.py很好用。 看到代码:

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))

但是,当我将代码包装到一个函数中并将其放入另一个文件config.py中时。 我在另一个文件中将该函数称为config.copy_default_files(),它不起作用。 因此,我在函数的末尾放置了raw_input(),以查看该函数是否已执行,并且确实打印了“ miao”,但未打印出文件列表。 并且没有文件生成或复制。 我很困惑,有人可以向我解释吗? 任何帮助将不胜感激。 让我知道您是否需要更多信息。 非常感谢!

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                 

仅仅定义功能是不够的。 您还需要调用它:

copy_default_files()

要么

config.copy_default_files()

(取决于您是将config.py作为脚本运行还是作为模块导入)。

暂无
暂无

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

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