Python 3.5:根据文件名将文件移动到文件夹
Python 3.5: Moving files to folder based on filenames
我有一个包含 10 张图像的文件夹,我希望根据它的当前文件名将它们移动到一个新文件夹中。我已经成功地将文件夹中的每个图像移动到一个新文件夹中,但我还没有弄清楚如何根据文件名移动文件,例如下面我想相应地移动图像。
- 1600_01.jpg ---> 文件夹 1
- 1700_01.jpg ---> 文件夹 1
- 1800_02.jpg ---> 文件夹 2
- 1900_02.jpg ---> 文件夹 2
- 2000_03.jpg ---> 文件夹 3
- 2100_03.jpg ---> 文件夹 3
到目前为止,这是我将文件夹中的整个文件移动到我想要的目标的代码。
# Moving Files from one place to another
import shutil
import os
sourcefile = 'Desktop/00/'
destination = 'Desktop/00/d'
# Loading the files from source
files = os.listdir(path=sourcefile)
# Reading the files in folder
for f in files:
shutil.move(sourcefile+f, destination)
此时您只需根据最后一位修改目的地即可:
for f in files:
folder_number = f.split('.')[0][-1]
shutil.move(sourcefile+f, destination + '/' + folder_number + '/' + f)
我有一个包含 10 张图像的文件夹,我希望根据它的当前文件名将它们移动到一个新文件夹中。我已经成功地将文件夹中的每个图像移动到一个新文件夹中,但我还没有弄清楚如何根据文件名移动文件,例如下面我想相应地移动图像。
- 1600_01.jpg ---> 文件夹 1
- 1700_01.jpg ---> 文件夹 1
- 1800_02.jpg ---> 文件夹 2
- 1900_02.jpg ---> 文件夹 2
- 2000_03.jpg ---> 文件夹 3
- 2100_03.jpg ---> 文件夹 3
到目前为止,这是我将文件夹中的整个文件移动到我想要的目标的代码。
# Moving Files from one place to another
import shutil
import os
sourcefile = 'Desktop/00/'
destination = 'Desktop/00/d'
# Loading the files from source
files = os.listdir(path=sourcefile)
# Reading the files in folder
for f in files:
shutil.move(sourcefile+f, destination)
此时您只需根据最后一位修改目的地即可:
for f in files:
folder_number = f.split('.')[0][-1]
shutil.move(sourcefile+f, destination + '/' + folder_number + '/' + f)