在Python中使用通配符移动文件 [英] Moving files with Wildcards in Python

查看:458
本文介绍了在Python中使用通配符移动文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试将所有以"A"开头的文件移至某个目录.现在我现在Windows命令提示符不支持此方法:

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

但是结合Python可以找到一种方法吗?还是我必须浏览每个单独的文件? 如:

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!

推荐答案

在Windows上:此示例将以"A"开头的文件从"C:\ 11"移动到"C:\ 2"

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

选项1::如果您正在使用批处理文件,请如下所示创建批处理文件(movefiles.bat):

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

从python脚本执行此批处理文件,如下所示:

Execute this batch file from python script as shown below:

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

选项2: 使用全局&闭嘴

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

如果我们要move所有filesdirectory以A开头:

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

基于@eryksun的注释,如果仅需要移动以A开头的files,并且在这种情况下,目录将被忽略.我添加了if not os.path.isdir(data):.

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

这篇关于在Python中使用通配符移动文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆