在这个例子中如何将变量传递给函数?

时间:2015-10-05 00:17:44

标签: python function

我写了一个非常基本的脚本来清理我的下载文件夹,一切正常,但我没有使用任何功能。

为了清理一下并使其更有条理,我尝试创建函数并将目录路径作为变量" cleaningpath"传递,但我认为我做错了。

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'

1 个答案:

答案 0 :(得分:2)

错误指的是:

    location1 = join(cleaningpath,item)

此行不起作用,因为cleaningpath是文件名列表,而不是字符串。我想你希望你的全局变量path作为join的第一个参数。

您在其他功能中遇到同样的问题:

            os.remove(join(cleaningpath,item))