我寫了一個非常基本的腳本來清理我的下載文件夾,一切正常,但我沒有使用任何功能。如何在本例中將變量傳遞給函數?
爲了清理一些東西,並使其更加有組織,我嘗試創建函數並將目錄路徑作爲變量「清理路徑」傳遞,但我認爲我做了一些不正確的事情。
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'
究竟是不是工作?任何錯誤消息? – tijko
我想你試圖'.join'列表變量,而不是目錄路徑的名稱。 – tijko