【问题标题】:I can't manage to move files properly in Python我无法在 Python 中正确移动文件
【发布时间】:2020-10-20 18:53:17
【问题描述】:

所以我制作了这个脚本来将我的桌面文件分类到文件夹中:

# 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() 命令甚至不会返回不移动的那些。有什么想法吗?

【问题讨论】:

  • 权限问题?
  • 您可以使用一些日志记录机制来查看哪些并深入了解未移动的那些?
  • 我刚刚看到很多文件没有移动,因为目标文件夹中已经有一个同名的文件。但是,当我想移动快捷方式(.lnk 扩展名)时,我仍然遇到问题,有些会移动,有些不会。
  • 它有什么规律吗?扩展名是否在较低的情况下?你有打开文件吗?你有任何错误吗?尝试添加一个打印语句,看看您认为正在尝试移动的内容是否真的在尝试。
  • Hoang Pham,我真的不知道你指的是哪种日志记录机制。

标签: python


【解决方案1】:

由于 os.listdir() 没有列出一些 *.lnk 文件,我假设它们在用户的桌面目录中不可用。

原因可能是这些文件存储在“公共桌面”中,即 c:\Users\Public\Desktop,并在所有用户之间共享。 由于您只针对当前用户 (userhome = os.path.expanduser('~')),公共桌面对您的代码保持“隐藏”。

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 2014-02-19
    • 2021-03-31
    • 2014-01-23
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    相关资源
    最近更新 更多