niv*_*ckz 5 python file-io python-2.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)
Run Code Online (Sandbox Code Playgroud)
我已经玩了很多,但没有用。在此最新版本中,运行程序时遇到以下错误:
追溯(最近一次通话最近):在shutil.move(源,目标)中的文件“ pngmove_2.0.py”,第23行,文件“ /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'))
Run Code Online (Sandbox Code Playgroud)
这可以将我的“ Test_Folder”文件夹重命名为“ Archive”。但是,它将移动文件夹中的所有文件,而不是移动以'.png'结尾的文件。
小智 6
另一种选择是使用 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)
Run Code Online (Sandbox Code Playgroud)
不过,如果您使用 glob 或 os.listdir,请记住为源文件和目标设置完整路径。
您正在尝试移动整个源文件夹,需要指定文件路径
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))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8008 次 |
最近记录: |