如何在本例中将变量传递给函数?
问题描述:
我写了一个非常基本的脚本来清理我的下载文件夹,一切正常,但我没有使用任何功能。如何在本例中将变量传递给函数?
为了清理一些东西,并使其更加有组织,我尝试创建函数并将目录路径作为变量“清理路径”传递,但我认为我做了一些不正确的事情。
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