python 部分文件、目录操作

本文介绍使用Python进行文件系统操作的方法,包括获取当前目录、创建和删除目录、文件复制与移动等常见任务。同时,还提供了如何重命名文件、判断文件或目录是否存在等功能的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取当前目录名
path = getcwd()

示例:

import os
path = os.getcwd()
print(path)

输出

D:\专业文档\learnpython\自用\整理目录

创建目录

示例
improt os
os.mkdir(‘D:\专业文档\temp’)


删除目录

示例

os.rmdir('D:\\专业文档\\temp')

创建新空白文件

示例:

os.mknod('test.txt')

复制文件:
shutil.copyfile()       

复制文件夹:
shutil.copytree()   

重命名文件(目录)
os.rename("oldname","newname") 

移动文件(目录)
shutil.move() 
语法:
shutil.move(src, dst, copy_function=copy2)
传入参数

src ———- 需要移动的文件或目录
dst ———- 目标

官方文档

Recursively move a file or directory (src) to another location (dst) and return the destination.
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dstusing copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.
If copy_function is given, it must be a callable that takes two arguments src and dst, and will be used to copy src to dest if os.rename() cannot be used. If the source is a directory, copytree() is called, passing it the copy_function(). The default copy_function is copy2(). Using copy() as the copy_function allows the move to succeed when it is not possible to also copy the metadata, at the expense of not copying any of the metadata.
Changed in version 3.3: Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv. Now returns dst.
Changed in version 3.5: Added the copy_function keyword argument.


删除文件
os.remove()

删除空目录
os.rmdir()

删除目录
shutil.rmtree("dir")    

转换目录
os.chdir("path")    

判断对象是否存在
os.path.exists("goal") 
官方文档

Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to executeos.stat() on the requested file, even if the path physically exists.
Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.
Changed in version 3.6: Accepts a path-like object.


判断对象是否是目录
os.path.isdir("goal")    

判断对象是否是文件
os.path.isfile("goal")    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值