Reputation: 160
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!
Upvotes: 2
Views: 11299
Reputation: 2984
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\\")
Upvotes: 4