如何使用python3.7.0中的os模块移动同名文件

2024-09-29 04:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用python3.7.0中的os模块将具有类似名称的文件从一个目录移动到另一个目录。例如,我有一个名为A1B1、A1B2、A2B1、A2B2等的文本文件。如何移动名为A1的目录中名为A1Bn(n=1,2,3…)的文件和名为A2的目录中名为A2Bn(n=1,2,3…)的文件。如何检查文件名。 谢谢。。。你知道吗


Tags: 模块文件目录名称a2os文件名a1
3条回答

使用globosshutil也可以使用):

import glob
import os

a1_files = glob.glob('A1*')
a2_files = glob.glob('A2*')

for filename in a1_files:
    os.rename(filename, os.path.join('A1', filename))

for filename in a2_files:
    os.rename(filename, os.path.join('A2', filename))

下面是一个经过调整的脚本,我不久前使用它来实现类似的功能:

from os import getcwd
from os import listdir
from os import makedirs

from os.path import join
from os.path import exists
from os.path import abspath

from shutil import move

current_path = getcwd()

for file in listdir("."):
    if file.startswith("A"):
        full_path = abspath(file)
        folder_prefix = file[:2]

        folder_path = join(current_path, folder_prefix)
        if not exists(folder_path):
            makedirs(folder_path)

        move(full_path, folder_path)

它复制当前目录中以A开头的所有文件,并将它们移动到各自的文件夹中。如果文件夹不存在,它也会预先生成文件夹。您可以通过包含自己的路径来根据自己的喜好进行调整,但它显示了总体思路。你知道吗

import os

base_path = "/path/to/files/"
filenames = os.listdir(base_path)

for f in filenames:
    source = base_path + f
    destination = base_path + f[:2] + "/" + f
    os.rename(source, destination)

相关问题 更多 >