2015-11-18 29 views
0

我想: 編寫一個腳本,它將一個目錄路徑作爲命令行參數,然後遍歷該路徑的所有子目錄,查找擴展名爲「.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

回答

0

您的代碼表示shutil.copy2(f, tmp/pyfiles),我相信它意味着是

shutil.copy2(f, 'tmp/pyfiles')

+0

當我添加引號時,我仍然得到一個錯誤,但更復雜的方式說明「沒有這樣的文件或目錄:'theo.py'」這是其中一個文件應該完全複製。 – Phillsss

+0

該文件確實存在,因爲它是用於查看腳本是否正在工作的測試文件之一。同時,我發現了以下內容: 該腳本適用於命令行中給出的路徑中的文件。但是,theo.py文件是此給定路徑中目錄中的文件。這顯然應該被複制,但顯然是出了問題的地方..?順便說一句,謝謝你的幫助:) :) – Phillsss

+0

這是因爲'f'只包含文件名。 'shutil.copy2'需要文件的完整路徑。 – DeepSpace

0

當您使用 os.walk() 方法時,會丟失文件完整路徑的跟蹤。我要做的就是使用方法 os.listdir() 分析每個目錄,然後複製每個文件並考慮其絕對路徑。像這樣的:

for root, dirs, files in os.walk(rootdir): 
    for dir in dirs:   
     for f in os.listdir(dir):   
      if os.path.splitext(f)[1] in ['.py']:              
       shutil.copy2(os.path.join(root, dir, f), "tmp/pyfiles") 

我希望這可以幫助,也許有一個更乾淨的解決方案。

0

按照你所說的做,你必須檢查根目錄是否存在,並且如果不創建新目錄,就可以刪除所有東西。

dir複製到你的,你必須檢查文件dir該文件名與.py結束,然後用根路徑替換目錄路徑和匹配文件的內容創建根目錄的新文件。
如果我們在dir找到一個目錄,我們應該在根目錄下創建一個新目錄。
之後,只需要調用的函數遞歸的所有內容複製的dir tothe根目錄

import os, sys 


rootdir = sys.argv[1] 
PATH = "/tmp/pyfiles/" 

def check(path, _file): 
    global rootdir, PATH 

    for item in os.listdir(path): 
     newpath = os.path.join(path, item) 
     if os.path.isdir(newpath): 
      os.mkdir(os.path.join(PATH, newpath.replace(rootdir, ''))) 
      check(newpath, _file) 
     else: 
      if item.endswith(_file): 
       source = open(newpath, 'r') 
       print os.path.join(path, newpath.replace(rootdir, '')) 
       output = open(os.path.join(PATH, newpath.replace(rootdir, '')), 'w') 
       output.write(source.read()) 
       output.close() 
       source.close() 


if __name__ == '__main__': 
    if os.path.isdir(PATH): 
     for root, dirs, files in os.walk(PATH, topdown=False): 
      for name in files: 
       os.remove(os.path.join(root, name)) 
      for name in dirs: 
       os.rmdir(os.path.join(root, name)) 
     os.rmdir(PATH) 

    os.mkdir(PATH) 

    check(rootdir, '.py') 

我希望這將是有益的。