python文件操作、文件操作、读写文件、写模式

with读取文件数据内容

with open(filepath,mode,encoding) as file:
    #具体操作,例如:
    print(file.read())
    #查看文件所有的内容。    
with:Python中的一个上下文管理器,用于简化资源的管理和释放。它可以用于任意需要进行资源分配和释放的情境,比如文件操作、数据库连接等。
open:open()内置函数用于打开文件,并返回一个文件对象。它接受两个参数:文件名和打开模式。
filepath:这是你要打开的文件的路径。
mode:打开模式(mode),用于指定文件的操作模式。

encoding:

这是用于读取或写入文件的字符编码。常见的编码有:

'utf-8':UTF-8编码,广泛使用的跨平台编码。

'ascii':ASCII编码,仅支持英文字符的编码方式。

'latin-1':Latin-1编码,支持ISO-8859-1字符集的编码方式。

'gbk':GBK编码,用于中文字符的编码方式。

'utf-16':UTF-16编码,用于较大字符集的编码方式。

如果不指定encoding参数,默认使用系统的默认编码方式。一般情况下,推荐使用UTF-8编码,因为它具有较广的支持和兼容性。

as:

as关键字用于给导入的模块起一个别名。

as关键字的作用是提供更简洁、易读的方式来使用变量或模块,并且可以避免命名冲突。

mode操作模式

语        法  说明        
r:(只读模式)只读模式。默认模式。适用于读取文件。
rb:(只读模式)读取二进制数据,例如图像、音频等文件。其中r表示只读操作,b表示以二进制格式打开文件。
w:(写入模式)写入模式。覆盖写入文本内容。如果文件不存在,则会创建一个新文件。
wb:(写入模式)覆盖写入二进制数据内容。如果文件不存在,则会创建一个新文件。
a:(写入模式)追加模式。在文件末尾追加内容。如果文件不存在,则会创建一个新文件。
x:独占创建模式。如果文件已存在,则会引发FileExistsError异常。
b:二进制模式。用于读取或写入二进制文件。
t:文本模式。默认模式,用于读取或写入文本文件。

+:

更新模式。打开文件用于读写。可以与其他模式组合使用,如'r+''w+''a+'

读语法

语法说明
read()

一次性读取整个文件的内容.

readline()

每次读取一行, 包括行尾的换行符 \ n, 当读取到文件结尾时将返回一个空字符串.

readlines()

一次性读取文件的所有行,并将每行内容作为一个字符串元素存放在列表.

写语法

语法说明
write(date)写入的数据内容,data必须是字符串string
读案例 
with open("csdn.py","r") as file:
    print(file.read())
#读取csdn.py文件中全部的内容。
追加写入案例
with open("jingyu","a") as file:
    file.write("Welcome to csdn jingyu飞鸟 Blog\n")
#向jingyu文件中追加写入内容。

\n是换行,如果没有\n的话情况就是这样的。 

 

覆盖写入案例
with open("jingyu","w") as file:
    file.write("Wait for you, hold my hand lightly.\n")
复制文本文件内容
with open("/jingyu/one.txt","r") as o,open("/jingyu/two.txt","r") as t:
    o.write(t.read())
复制二进制文件
with open("/jingyu/jingyu.png","rb") as o, open("/jingyu/jingyutwo.png","wb") as t:
    o.write(w.read())

文件及文件夹操作

序号

命令

说明

1

os.getcwd()

获取当前目录地址

2

os.chdir(path)

切换目录

3

os.path.exists(filename/path)

判断文件或文件夹是否存在

4

os.path.basename(path)

获取文件名

5

os.path.dirname(path)

获取路径

6

os.path.split(path)

获取路径的目录和文件名

7

os.path.splitext(path)

分离扩展名

8

os.path.getsize(path)

获取文件大小

9

os.stat(path)

获取文件属性

10

os.mknod(filename)

创建文件

11

os.mkdir(path)

创建文件夹

12

os.makedirs(path)

创建多级文件夹

13

shutil.copyfile(filepath,filepath)

复制文件

14

shutil.copytree(path,path)

复制文件夹

15

shutil.move(filepath,path)

移动文件

16

os.listdir()

查看目录列表

17

os.remove(filepath)

删除文件

18

os.rmdir(path)

删除空文件夹(空)

19

os.removedirs(path)

删除多级文件夹(空)

20

shutil.rmtree(path)

删除单/多级文件夹(非空)

21

os.path.isfile(filepath)

是否为文件

22

os.path.isdir(path)

是否为目录

案例:

 

import os

# 获取当前目录地址
print(os.getcwd())

# 切换目录
os.chdir("/root/temp")
print(os.getcwd())

# 创建文件
if not os.path.exists("/root/temp/demo01.txt"):
    os.mknod("demo01.txt")
    
# 获取文件名
print(os.path.basename("/root/temp/demo01.txt"))

# 获取路径
print(os.path.dirname("/root/temp/demo01.txt"))

# 获取路径的目录名和文件名
print(os.path.split("/root/temp/demo01.txt"))

# 分离扩展名
print(os.path.splitext("/root/temp/demo01.txt"))

# 获取文件的大小
print(os.path.getsize("/root/temp/demo01.txt"))

# 获取文件的属性
_file_detail = os.stat("/root/temp/demo01.txt")
print(os.stat("/root/temp/demo01.txt"))

# 获取文件大小
print(_file_detail.st_size)

# 获取文件创建时间
print(_file_detail.st_ctime)

# 获取文件修改时间
print(_file_detail.st_mtime)

# 获取文件访问时间
print(_file_detail.st_atime)

# 创建文件夹
if not os.path.exists("/root/temp"):
    os.mkdir("/root/temp")
    
# 创建多级文件夹
if not os.path.exists("/root/my/demo"):
    os.makedirs("/root/my/demo")
    
# 查看目录"列表
os.chdir("/root")
print(os.listdir())

# 创建文件
if not os.path.exists("/root/my/demo/test01.txt"):
    os.chdir("/root/my/demo")
    os.mknod("test01.txt")
    
# 写入数据
_file = open("/root/my/demo/test01.txt", "w",
             encoding="UTF-8")
_file.write("i like python....")
_file.close()

# 删除一个指定的空文件夹
os.rmdir("/root/my")
os.rmdir("/root/rm")

# 删除一个指定的多级目录
os.removedirs("/root/my")  # OSError: [Errno 39]
os.removedirs("/root/1/2")
# 删除目录(非空也可)

import shutil

shutil.rmtree("/root/my")
print(os.path.isfile("/root/data/123.png"))
print(os.path.isdir("/root/data"))
print(os.path.isfile("/root/data"))
print(os.path.isdir("/root/data/a.txt"))

# 复制文件
shutil.copyfile("/root/data/hello.txt",
                "/root/data/hellobf1.txt")
                
# 复制文件夹
shutil.copytree("/root/data", "/root/mytest")

# 移动文件
shutil.move("/root/data/123.png",
            "/root/files/temp")
            
# 删除文件
os.remove("/root/files/temp/123.png")
  • 21
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jingyu飞鸟

醒来觉得甚是爱你。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值