我想: 編寫一個腳本,它將一個目錄路徑作爲命令行參數,然後遍歷該路徑的所有子目錄,查找擴展名爲「.py」的文件,將每個文件複製到文件系統中的臨時目錄(例如/ tmp/pyfiles)。您的腳本應該檢查臨時目錄的存在,如果它已經存在,則將其刪除;它應該在開始複製文件之前創建一個新的目錄。查找文件,複製到新目錄python
我有這樣的:
#!/usr/bin/env python
import os, sys
import shutil
#import module
rootdir = sys.argv[1]
#take input directory
if os.path.exists('tmp/pyfiles'):
shutil.rmtree('tmp/pyfiles')
if not os.path.exists('tmp/pyfiles'):
os.makedirs('tmp/pyfiles')
#check whether directory exists, if it exists remove and remake, if not make
for root, dirs, files in os.walk(rootdir):
for f in files:
if os.path.splitext(f)[1] in ['.py']:
shutil.copy2(f, tmp/pyfiles)
#find files ending with .py, copy them and place in tmp/pyfiles directory
我得到這個錯誤:
Traceback (most recent call last):
File "seek.py", line 20, in <module>
shutil.copy2(f, tmp/pyfiles)
NameError: name 'tmp' is not defined
誰能幫我出:) THX
當我添加引號時,我仍然得到一個錯誤,但更復雜的方式說明「沒有這樣的文件或目錄:'theo.py'」這是其中一個文件應該完全複製。 – Phillsss
該文件確實存在,因爲它是用於查看腳本是否正在工作的測試文件之一。同時,我發現了以下內容: 該腳本適用於命令行中給出的路徑中的文件。但是,theo.py文件是此給定路徑中目錄中的文件。這顯然應該被複制,但顯然是出了問題的地方..?順便說一句,謝謝你的幫助:) :) – Phillsss
這是因爲'f'只包含文件名。 'shutil.copy2'需要文件的完整路徑。 – DeepSpace