2015-10-05 84 views
0

我寫了一個非常基本的腳本來清理我的下載文件夾,一切正常,但我沒有使用任何功能。如何在本例中將變量傳遞給函數?

爲了清理一些東西,並使其更加有組織,我嘗試創建函數並將目錄路徑作爲變量「清理路徑」傳遞,但我認爲我做了一些不正確的事情。

import sys 
import os 
from os import listdir 
from os.path import join 
import shutil 


#Variables 
path="/Users/OwlFace/downloads" 
cleaningpath=os.listdir(path) 


def deleterars(cleaningpath): 
    rarcounter=0 
    for item in cleaningpath: 
     if item.endswith(".rar"): 
      os.remove(join(cleaningpath,item)) 
      rarcounter+=1 
    print "you have succesfully removed", rarcounter, "rar files" 


def organizemusic(cleaningpath): 
    mp3counter=0 
    if not os.path.exists("/Users/OwlFace/downloads/NewMusic/"): 
     os.makedirs("/Users/OwlFace/downloads/NewMusic/") 
    mp3folder="/Users/OwlFace/downloads/NewMusic/" 

    for item in cleaningpath: 
     if item.endswith(".mp3"): 
      location1 = join(cleaningpath,item) 
      location2 = join(mp3folder,item) 
      shutil.move(location1, location2) 
      mp3counter+=1 
    print "you have succesfully moved", mp3counter, "mp3's to the music folder" 


if __name__ == "__main__": 
    deleterars(cleaningpath) 
    organizemusic(cleaning path) 

錯誤:

Traceback (most recent call last): 
    File "cleaningscript.py", line 39, in <module> 
    organizemusic(cleaningpath) 
    File "cleaningscript.py", line 30, in organizemusic 
    location1 = join(cleaningpath,item) 
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 70, in join 
    elif path == '' or path.endswith('/'): 
AttributeError: 'list' object has no attribute 'endswith' 
+0

究竟是不是工作?任何錯誤消息? – tijko

+0

我想你試圖'.join'列表變量,而不是目錄路徑的名稱。 – tijko

回答

2

錯誤指的是線路:

location1 = join(cleaningpath,item) 

此行不起作用,因爲cleaningpath是文件名,而不是字符串列表。我想你想要你的全局變量path作爲join的第一個參數。

您的其他功能同樣的問題,在這條線:

  os.remove(join(cleaningpath,item)) 
+0

我是個白癡。謝謝! – david

+0

我可能不應該將其命名爲「清潔路徑」 – david