[英]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.