Moving files with Wildcards in Python

喜你入骨 提交于 2019-12-23 04:56:06

问题


So I am trying to move say all files starting with "A" to a certain directory. Now I now Windows command prompt does not support this method:

move A* A_Dir

But could this combined with Python find a way? Or am I gonna have to go through each individual file? Such as:

contents=os.listdir('.')
for file in content:
    if file[0] == 'A':
        os.system("move %s A_Dir" % file)

... etc. Is there any other solution that is more simpler and quicker? -Thanks!


回答1:


On Windows: This example moves files starting with "A" from "C:\11" to "C:\2"

Option #1: if you are using batch file, create batch file (movefiles.bat) as show below:

movefiles.bat:

move /-y "C:\11\A*.txt" "C:\2\"

Execute this batch file from python script as shown below:

import os
batchfile = "C:\\1\\movefiles.bat"
os.system( "%s" % batchfile)

Option #2: using glob & shutil

import glob
import shutil
for data in glob.glob("C:\\11\\A*.txt"):
    shutil.move(data,"C:\\2\\")

If we want to move all files and directory starting with A:

import glob
import shutil

for data in glob.glob("C:\\11\\A*"):
        shutil.move(data,"C:\\2\\")

Based on @eryksun comment, I have added if not os.path.isdir(data):, if only files starting with A are required to be moved and in this case, directory will be ignored.

import glob
import shutil
import os
for data in glob.glob("C:\\11\\A*"):
    if not os.path.isdir(data):
        shutil.move(data,"C:\\2\\")


来源:https://stackoverflow.com/questions/28913088/moving-files-with-wildcards-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!