【问题标题】:Moving specific file types with Python使用 Python 移动特定文件类型
【发布时间】:2014-06-26 16:30:12
【问题描述】:

我知道这对你们中的许多人来说会很容易令人沮丧。我刚开始学习 Python,需要一些基本文件处理方面的帮助。

我拍摄了很多屏幕截图,最终出现在我的桌面上(因为这是默认设置)。我知道我可以更改屏幕截图设置以自动将其保存在其他位置。但是,我认为这个程序将是教我如何对文件进行排序的好方法。我想使用 python 自动对桌面上的所有文件进行排序,识别以 .png 结尾的文件(屏幕截图的默认文件类型),然后简单地将其移动到我命名为“存档”的文件夹中。

这是我目前得到的:

import os
import shutil
source = os.listdir('/Users/kevinconnell/Desktop/Test_Folder/')
destination = 'Archive'
for files in source:
    if files.endswith('.png'):
        shutil.move(source, destination)

我已经玩了很多,但无济于事。在这个最新版本中,我在运行程序时遇到以下错误:

Traceback(最近一次调用最后一次): 文件“pngmove_2.0.py”,第 23 行,在 shutil.move(源,目的地) 文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py”,第 290 行,在移动中 TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到列表

我的印象是源和目标所需的正确约定/语法存在某种问题。但是,到目前为止,我一直无法找到有关如何修复它的太多帮助。我使用 os.path.abspath() 来确定您在上面看到的文件路径。

提前感谢您在保持我的理智方面提供的任何帮助。

最新更新

我相信我已经非常接近查明真相了。我敢肯定,如果我继续玩它,我会弄清楚的。只是为了让所有帮助我的人都得到更新......

这是我正在使用的当前代码:

import os
import shutil
sourcepath ='/Users/kevinconnell/Desktop/'
source = os.listdir(sourcepath)
destinationpath = '/Users/kevinconnell/Desktop/'
for files in source:
    if files.endswith('.png'):
        shutil.move(os.path.join(sourcepath,'Test_Folder'), os.path.join(destinationpath,'Archive'))

这适用于将我的“Test_Folder”文件夹重命名为“Archive”。 但是,它会移动文件夹中的所有文件,而不是移动以“.png”结尾的文件。

【问题讨论】:

  • 看到你的来源是一个列表。包含许多文件,您必须移动源+文件,目标+文件
  • 你的移动总源文件夹。只需要移动文件
  • 答案是否解决了你的问题
  • 嘿,你理解错了,检查一下我更新了
  • 检查更新。它可以在我的系统中正常工作

标签: python python-2.7 file-io


【解决方案1】:

您正在尝试移动整个源文件夹,您需要指定文件路径

import os
import shutil
sourcepath='C:/Users/kevinconnell/Desktop/Test_Folder/'
sourcefiles = os.listdir(sourcepath)
destinationpath = 'C:/Users/kevinconnell/Desktop/Test_Folder/Archive'
for file in sourcefiles:
    if file.endswith('.png'):
        shutil.move(os.path.join(sourcepath,file), os.path.join(destinationpath,file))

【讨论】:

  • 我还建议使用 os.path.join 而不是 +
  • @AMacK 我已经告诉他出了什么问题,请更新我的答案。让我学得更好
  • @nivackz 我说由于您发送的源是文件列表但 shutill.move 需要单个文件,因此在哪里导致错误。这就是我的意思。他说他更喜欢使用 os.join.path 来加入源路径+文件名。请不要对你不利
  • 抱歉,我花了一点时间才回来。我认为您涵盖了我注意到的所有内容,尽管目标路径的开头缺少“/”。
  • @AMacK 感谢您的想法。真的 os.path.join 是必须的。有时 v 忘记正确使用斜线或将其作为特殊字符
【解决方案2】:

另一个选项是使用 glob 模块,它可以让您指定文件掩码并检索所需文件的列表。 应该很简单

import glob
import shutil

# I prefer to set path and mask as variables, but of course you can use values
# inside glob() and move()

source_files='/Users/kevinconnell/Desktop/Test_Folder/*.png'
target_folder='/Users/kevinconnell/Dekstop/Test_Folder/Archive'

# retrieve file list
filelist=glob.glob(source_files)
for single_file in filelist:
     # move file with full paths as shutil.move() parameters
    shutil.move(single_file,target_folder) 

不过,如果您使用 glob 或 os.listdir,请记住为源文件和目标设置完整路径。

【讨论】:

  • 更新后 - glob 可以轻松处理您的文件掩码问题。
  • 您的意思是文件列表中的 single_file 吗?
【解决方案3】:

基于@Gabriels 的回答。 我为此付出了一些努力,因为我喜欢将我的文件类型“分类”到文件夹中。我现在用这个。

我相信这就是你要找的东西,这很有趣

这个脚本:

  • 显示要移动的示例文件,直到您取消注释 shutil.move
  • 在 Python3 中
  • 在 MacOSX 上设计
  • 不会为您创建文件夹,它会引发错误
  • 可以查找和移动具有您想要的扩展名的文件
  • 可用于忽略文件夹
    • 包括目标文件夹,是否应嵌套在您的搜索文件夹中
  • 可以在我的Github Repo找到

终端示例:

$ python organize_files.py
filetomove: /Users/jkirchoff/Desktop/Screen Shot 2018-05-15 at 12.16.21 AM.png
movingfileto: /Users/jkirchoff/Pictures/Archive/Screen Shot 2018-05-15 at 12.16.21 AM.png

脚本:

我命名为organize_files.py

#!/usr/bin/env python3

# =============================================================================
# Created On  : MAC OSX High Sierra 10.13.4 (17E199)
# Created By  : Jeromie Kirchoff
# Created Date: Mon May 14 21:46:03 PDT 2018
# =============================================================================
# Answer for: https://stackoverflow.com/a/23561726/1896134 PNG Archive
# NOTE: THIS WILL NOT CREATE THE DESTINATION FOLDER(S)
# =============================================================================

import os
import shutil

file_extensn = '.png'
mac_username = 'jkirchoff'

search_dir = '/Users/' + mac_username + '/Desktop/'
target_foldr = '/Users/' + mac_username + '/Pictures/Archive/'
ignore_fldrs = [target_foldr,
                '/Users/' + mac_username + '/Documents/',
                '/Users/' + mac_username + '/AnotherFolder/'
                ]

for subdir, dirs, files in os.walk(search_dir):
    for file in files:
        if subdir not in ignore_fldrs and file.endswith(file_extensn):
            # print('I would Move this file: ' + str(subdir) + str(file)
            #       # + "\n To this folder:" + str(target_foldr) + str(file)
            #       )

            filetomove = (str(subdir) + str(file))
            movingfileto = (str(target_foldr) + str(file))
            print("filetomove: " + str(filetomove))
            print("movingfileto: " + str(movingfileto))

            # =================================================================
            # IF YOU ARE HAPPY WITH THE RESULTS
            # UNCOMMENT THE SHUTIL TO MOVE THE FILES
            # =================================================================
            # shutil.move(filetomove, movingfileto)

            pass
        elif file.endswith(file_extensn):
            # print('Theres no need to move these files: '
            #       + str(subdir) + str(file))
            pass
        else:
            # print('Theres no need to move these files either: '
            #       + str(subdir) + str(file))
            pass

【讨论】:

    【解决方案4】:
    import os
    import shutil
    Folder_Target = input("Path Target which Contain The File Need To Move it: ")
    File_Extension = input("What Is The File Extension ? [For Example >> pdf , txt , exe , ...etc] : ")
    Folder_Path = input("Path To Move in it : ")
    Transformes_Loges = input("Path To Send Logs Of Operation in : ")
    x=0
    file_logs=open(Transformes_Loges+"\\Logs.txt",mode="a+")
    
    for folder, sub_folder, file in os.walk(Folder_Target):
        for sub_folder in file:
            if os.path.join(folder, sub_folder)[-3:]==File_Extension:
               path= os.path.join(folder, sub_folder)
               file_logs.write(path+" =====================  Was Moved to ========================>> "+Folder_Path )
               file_logs.write("\n")
               shutil.move(path, Folder_Path)
               x+=1
    file_logs.close()
    print("["+str(x)+"]"+"File Transformed")
    

    【讨论】:

      猜你喜欢
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 2018-10-07
      相关资源
      最近更新 更多