如何根据文件名将文件移动到python中的特定目录? [英] How to move files based on their names to specific directories in python?

查看:50
本文介绍了如何根据文件名将文件移动到python中的特定目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 /user/local/ 的目录,里面有几个表单文件,jenjar.dat_1jenmis.dat_1>.还有另外一个目录/user/data,里面有表单的两个子目录,jenjarjenmis.我需要一个 Python 代码,它将 jenjar.dat_1 移动到 /user/datajenjar 目录中,类似地,jenmis.dat_1进入'/user/datajenmis目录.

I have a directory called /user/local/ inside which i have several files of the form, jenjar.dat_1 and jenmis.dat_1. There is another directory /user/data inside which there are two subdirectories of the form, jenjar and jenmis. I need a Python code that would move the jenjar.dat_1 into the jenjar directory of /user/data and similarly, jenmis.dat_1 into jenmis directory of '/user/data.

我猜 os 模块可以用于这种情况,但我很困惑.这里的大多数问题都没有展示 Pythonic 的方法来做到这一点.

I guess the os module would work for thus but I'm confused. Most of the questions here do not show a Pythonic way to do this.

我找到了解决方案

destination = '/user/local'
target = '/user/data'
destination_list = os.listdir(destination)
data_dir_list = os.listdir(target)
for fileName in destination_list:
   if not os.path.isdir(os.path.join(destination, fileName)):
       for prefix in data_dir_list:
           if fileName.startswith(prefix):
               shutil.copy(os.path.join(destination, fileName), os.path.join(target, prefix, fileName))

推荐答案

这应该可以解决问题

srcDir = '/user/local'
targetDir = '/user/data'
for fname in os.listdir(srcDir):
    if not os.path.isdir(os.path.join(srcDir, fname)):
        for prefix in ['jenjar.dat', 'jenmis.dat']:
            if fname.startswith(prefix):
                if not os.path.isdir(os.path.join(targetDir, prefix)):
                    os.mkdir(os.path.join(targetDir, prefix))
                shutil.move(os.path.join(srcDir, fnmae), targetDir)

这篇关于如何根据文件名将文件移动到python中的特定目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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