使用Python移动特定文件类型

7

我知道对于许多人来说,这将是非常简单的。我刚开始学习Python,并需要一些基本文件处理的帮助。

我经常截屏,这些截图最终会出现在我的桌面上(因为这是默认设置)。我知道我可以更改屏幕截图设置以自动保存到其他地方。然而,我认为这个程序将是教我如何分类文件的好方法。我想使用Python自动筛选桌面上的所有文件,识别那些以.png结尾的文件(截图的默认文件类型),并将其移动到我命名为“Archive”的文件夹中。

以下是我的进展:

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 (most recent call last): File "pngmove_2.0.py", line 23, in shutil.move(source, destination) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 290, in move TypeError: coercing to Unicode: need string or buffer, list found

我认为问题出在源文件和目标文件的正确命名上。然而,到目前为止,我一直无法找到有关如何解决此问题的帮助。我使用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'结尾的文件。


您需要移动整个源文件夹的内容,但只需要移动文件。 - sundar nataraj
答案解决了您的问题吗? - sundar nataraj
嘿,你误解了,看看我更新了什么。 - sundar nataraj
检查更新后,我的系统中运行没有错误。 - sundar nataraj
你可以从终端做同样的事情,你知道的... mv *.png Archive - MattDMo
显示剩余2条评论
4个回答

10

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

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
@AMacK,我已经向他展示了问题所在,请更新我的答案,这样我可以更好地学习。 - sundar nataraj
@nivackz,我是说错误是在哪里引起的,因为你发送的源是文件列表,但shutil.move需要单个文件。这就是我的意思。他说他更喜欢使用os.join.path来连接sourcepath+文件名。请注意,这并不针对你。 - sundar nataraj
抱歉让你久等了。我认为你已经涵盖了我注意到的一切,尽管目标路径开头缺少一个“/”符号。 - AMacK
1
@AMacK,感谢您的建议。os.path.join确实是必须的。有时候我们会忘记正确地添加斜杠,或者它会被视为特殊字符。 - sundar nataraj

7

另一个选择是使用 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,请记得为源文件和目标设置完整路径。


在您更新后,全局处理您的文件掩码问题变得非常容易。 - Gabriel M
1
你是不是想说filelist中的single_file? - birdmw

0
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")

0

基于@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://dev59.com/OH_aa4cB1Zd3GeqP4ISg#23561726 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接