我无法在Python中正确地移动文件

时间:2014-05-18 16:46:49

标签: python

所以我创建了这个脚本,将我的桌面文件排序到文件夹中:

# Desktop Organization Script

import os
import shutil

userhome = os.path.expanduser('~')
src = userhome + '/Desktop/'
dst = src+ 'org/'

f_exe = [".exe",".lnk"]
f_web = [".php",".html",".css"]
f_images = [".jpg",".jpeg",".png",".ico",".gif",".JPG"]
f_video = [".avi"]
f_music  = [".ogg",".wav",".mp3"]
f_document = [".txt",".pdf",".ppt",".pptx",".docx",".doc",".xls"]
f_multimedia = [".max",".m",".ase",".swf",".fla"]
f_zip = [".rar",".zip",".7z"]
f_book = [".epub"]
f_other = [".s2z",".url"]

formats = [f_exe,f_web,f_images,f_music,f_document,f_multimedia,f_zip,f_book,f_other,f_video]

def main(): 
    txtlist = os.listdir(src);
    for file in txtlist:
        sortFiles(file)

def sortFiles(file):        
    for group in formats:
        for format in group:
            if file.endswith(format):
                    if format in f_exe: directory = "Executables"
                    if format in f_web: directory = "Web Development"
                    if format in f_images: directory = "Images"
                    if format in f_music: directory = "Music"
                    if format in f_document: directory = "Documents"
                    if format in f_multimedia: directory = "Multimedia"
                    if format in f_zip: directory = "RARs and ZIPs"
                    if format in f_book: directory = "Books"
                    if format in f_other: directory = "Others"
                    if format in f_video: directory = "Videos"
                    if not os.path.exists(dst+directory+"/"):
                        os.makedirs(dst+directory+"/")
                    shutil.move(src+file,dst+directory+"/") 


main()

虽然这适用于大多数文件,但有时会有这些脚本不会移动的文件,即使它们与正确移动的文件共享扩展名。实际上,我只是在移动快捷方式时遇到问题(.lnk扩展名)。其中一些移动,其中一些不移动。 os.listdir()命令甚至不返回那些不移动的。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

由于os.listdir()未列出某些* .lnk文件,因此我认为它们在用户的桌面目录中不可用。

其原因可能是这些文件存储在“公共桌面”中,即 c:\ Users \ Public \ Desktop ,并在所有用户之间共享。 由于您仅定位当前用户(userhome = os.path.expanduser('〜')),因此公共Deskop仍“隐藏”在您的代码中。