python通配符怎么用_在Python中使用通配符移动文件

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!

解决方案

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\\")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值