[英]Trying to move files into subfolders with shutil.move()
I'm trying to make a code that takes all the files in one directory and organizes them into subdirectories. 我正在尝试编写一个将所有文件放在一个目录中并将它们组织到子目录中的代码。 ie 2017.2.3, 2016.2.5, 2015.5.6, 2014.3.5 into folders labeled 2017, 2016, 2015, 2014 within the original directory.
即将2017.2.3、2016.2.5、2015.5.6、2014.3.5放入原始目录中标记为2017、2016、2015、2014的文件夹中。 Using 2.7.13
使用2.7.13
The code I'm using is below: 我正在使用的代码如下:
import os, shutil
root_path = ('D:\Sigma\Rides')
folders = ['2016', '2017', '2018', '2019', '2020']
for folder in folders:
os.mkdir(os.path.join(root_path,folder))
source = os.listdir('D:\\Sigma\\Rides')
dest1 = ('D:\\Sigma\\Rides\\2016')
dest2 = ('D:\\Sigma\\Rides\\2017')
dest3 = ('D:\\Sigma\\Rides\\2018')
dest4 = ('D:\\Sigma\\Rides\\2019')
dest5 = ('D:\\Sigma\\Rides\\2020')
for files in source:
if (files.startswith('2016_')):
shutil.move(os.path.join(source, files), dest1)
if (files.startswith('2017')):
shutil.move(os.path.join(source, files), dest2)
if (files.startswith('2018')):
shutil.move(os.path.join(source, files), dest3)
if (files.startswith('2019')):
shutil.move(os.path.join(source, files), dest4)
if (files.startswith('2020')):
shutil.move(os.path.join(source, files), dest5)
This is the error I receieve: 这是我收到的错误:
Traceback (most recent call last):
File "D:\Documents\Programs\Sigma_File_Move.py", line 24, in <module>
shutil.move(os.path.join(source, files), dest1)
File "D:\Python27\ArcGIS10.4\lib\ntpath.py", line 65, in join
result_drive, result_path = splitdrive(path)
File "D:\Python27\ArcGIS10.4\lib\ntpath.py", line 116, in splitdrive
normp = p.replace(altsep, sep)
AttributeError: 'list' object has no attribute 'replace'
Any feedback would be greatly appreciated. 任何反馈将不胜感激。
The problem here is that you're trying to create the source file path by joining source
variable and files
. 这里的问题是,您正在尝试通过将
source
变量和files
连接在一起来创建源文件路径。 Here source
is a list of all the files and folders in your "Rides" directory. 这里的
source
是“ Rides”目录中所有文件和文件夹的列表。 It is not possible to join a list of files and folders to a folder name. 无法将文件和文件夹列表加入文件夹名称。 That is why the error is happening.
这就是为什么发生错误。
So replacing os.path.join(source, files)
to os.path.join(root_path, files)
should work for you. 因此,将
os.path.join(source, files)
替换为os.path.join(root_path, files)
应该适合您。
if (files.startswith('2016_')):
shutil.move(os.path.join(source, files), dest1)
should be changed to 应该更改为
if (files.startswith('2016_')):
shutil.move(os.path.join(root_path, files), dest1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.