龙空技术网

Python 初学者练习:移动文件或文件夹

信息科技云课堂 434

前言:

眼前朋友们对“apachemovefile函数”大概比较关切,我们都想要了解一些“apachemovefile函数”的相关知识。那么小编在网上收集了一些有关“apachemovefile函数””的相关内容,希望朋友们能喜欢,姐妹们一起来学习一下吧!

在本教程中,你将学习如何在 Python 中动文件或文件夹。

移动单个文件

使用 shutil.move() 方法将文件从一个文件夹永久移动到另一个文件夹。

「语法格式:」

shutil.move(source, destination, copy_function = copy2)

source:需要移动的源文件的路径。

destination:目标文件夹的路径。

copy_function:移动文件是将文件复制到新位置并删除原文件。此参数是用于复制文件的函数,其默认值为 copy2() ,这可以是任何其他函数,如 copy()、copyfile()。

import shutilsrc_path=r"C:\temp1\abc.txt"dst_path=r"C:\temp2\abc.txt"shutil.move(src_path,dst_path)print("完成移动文件!")

如果目标路径存在同名文件,则文件将被覆盖。如果在移动文件时指定的目标路径不存在,将创建一个新目录。

移动文件并重命名

假设目标路径中已存在同名文件。在这种情况下,可以通过重命名文件来完成移动。这需要检查目标文件夹中是否存在同名文件。

import osimport shutilsrc_path=r"C:\temp1\\"dst_path=r"C:\temp2\\"file_name='abc.txt'# 检查目标路径是否存在同名文件if os.path.exists(dst_path+file_name):    # 分割提取文件名和扩展名    data=os.path.splitext(file_name)    only_name=data[0]    extension=data[1]    # 设置新文件名    new_base=only_name+'_new'+extension    new_name=os.path.join(dst_path,new_base)    shutil.move(src_path+file_name,new_name)    print(f"文件已存在,重命名为{new_base}")else:    shutil.move(src_path+file_name,dst_path+file_name)
从文件夹中移动所有文件

将所有文件从一个文件夹移动到另一个文件夹。使用 os.listdir()方法获取源文件夹中的所有文件。使用 for 循环遍历文件列表以获取各个文件名,使用 shutil.move()方法完成操作。

import osimport shutilsrc_path=r"C:\temp1\\"dst_path=r"C:\temp2\\"for file_name in os.listdir(src_path):    source=src_path+file_name    destination=dst_path+file_name    if os.path.isfile(source):        shutil.move(source,destination)        print('移动:',file_name)
移动指定的多个文件
import shutilsrc_path=r"C:\temp1\\"dst_path=r"C:\temp2\\"files=['abc.txt','def.txt']for file in files:    source=src_path+file    destination=dst_path+file    shutil.move(source, destination)    print('移动:', file)
使用通配符移动匹配的文件

glob 模块是 Python 标准库的一部分,遵循特定模式查找文件和文件夹。可以使用通配符进行匹配,返回匹配的文件或文件夹列表。

#移动所有txt文件import globimport osimport shutilsrc_path=r"C:\temp1\\"dst_path=r"C:\temp2\\"pattern = "\*.txt"files=glob.glob(src_path+pattern)for file in files:    file_name=os.path.basename(file)    shutil.move(file,dst_path+file_name)    print('移动:',file)
#移动文件名以a开头的所有文件import globimport osimport shutilsrc_path=r"C:\temp1\\"dst_path=r"C:\temp2\\"pattern=src_path+"\\a*"print(pattern)for file in glob.iglob(pattern,recursive=True):    file_name=os.path.basename(file)    shutil.move(file,dst_path+file_name)    print('移动:',file)

「文章创作不易,如果您喜欢这篇文章,请关注、点赞并分享给朋友。如有意见和建议,请在评论中反馈!」

标签: #apachemovefile函数