Python学习(十六)——文件操作

文件操作

操作文件的步骤:

  1. 打开文件
  2. 对文件进行操作,保存
  3. 关闭文件

打开

  • 语法:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

file:要打开的文件名字(或者说是路径)
Ctrl+shift+c 绝对路径
… 表示上一级\

filename = '../day16/demo.txt'	# 结果:<_io.TextIOWrapper name='../day16/demo.txt' mode='r' encoding='cp936'>
# filename = 'D:\study\pythonproject\day16\demo.txt'	# 结果:<_io.TextIOWrapper name='E:\\PY\\1python_basic\\study\\day16\\demo.txt' mode='r' encoding='cp936'>
demo = open(filename)
print(demo)

对于路径写的时候 在路径字符串前面加一个r,可以规避反斜杠。

打开模式效果
r以读方式打开,文件必须存在
w以写方式打开,文件不存在则创建,存在清空原有内容
a以追加模式打开,文件不存在则创建,存在则继续进行写操作
r+以读写模式打开 文件必须存在
w+以读写模式打开文件,不存在则创建,存在清空原有内容
a+追加并可读模式,文件不存在则创建,存在则继续进行写操作
rb以二进制读模式打开 同r
wb以二进制写模式打开 同w
ab以二进制追加模式打开 同a
rb+以二进制读写模式打开 同r+
wb+以二进制读写模式打开 同w+
ab+以二进制读写模式打开 同a+

关闭

close()
with open…as 语句 执行完可以自动关闭。

filename = r'../day15/demo.txt'
with open(filename) as f:
    print(f.read())
print(f.read())  # 会报错,with执行结束就会自动close关闭掉
# 结果:ValueError: I/O operation on closed file.
filename = '../day16/demo.txt'
demo = open(filename)
print(demo)

content = demo.read()
print(content)
print(type(content))
demo.close()
# 结果:hello,world
#		浣犲ソ涓栫晫
#		<class 'str'>

读取

文件分类

  1. 纯文本文件(使用utf-8等编码编写的文本文件)
  2. 二进制文件(音乐,图片,视频)

read()

read() 读取,括号里有参数,指定读取字符的数量,默认值是-1就是读取文件中所有的字符。

filename = r'demo.txt'
with open(filename, encoding='utf-8') as f:
    content = f.read(4)
    content = f.read(4)
    content = f.read(4)
    content = f.read()  # 如果读取完了文件,还继续读,就会返回空字符串
    print(content)
    print(len(content))   # 字符个数(换行 \n算一个字符)
# 结果:hello,world
#		hello,world
#		hello,world
#		你好世界
#		40
# 读取一个大文件的规范写法
filename = r'demo.txt'
with open(filename,encoding='utf-8') as f:
    all_content = ''
    while True:
        content = f.read(3)
        if content == '':
            break
        all_content += content
        print(content, end="")
print(all_content)
# 结果:hello,world
#		hello,world
#		hello,world
#		hello,world
#		你好世界hello,world
#		hello,world
#		hello,world
#		hello,world
#		你好世界

readline()

filename = r'demo.txt'
with open(filename,encoding='utf-8') as f:
    # 因为print自带换行 ,所以用参数end格式化换行
    print(f.readline(),end="")  # 读取一行内容
    print(f.readline(),end="")
    print(f.readline(),end="")
    print(f.readline(),end="")
# 结果:hello,world
#		hello,world
#		hello,world
#		hello,world
#		你好世界   

readlines()

filename = r'demo.txt'
with open(filename,encoding='utf-8') as f:
    l = f.readlines()  # 一行一行的读完内容
    print(l[1:3])
# 结果:['hello,world\n', 'hello,world\n', 'hello,world\n']

写入

  • 语法:open(file,mode='r')
写入模式效果
r可读,读取文本文件(默认)
w可写,会默认覆盖文件,如果文件不存在的话就会创建文件
a追加,如果文件不存在也会创建,如果文件存在则追加
b读取二进制文件

write() :括号里面传递的是字符串
write的返回值就是你写入的字符串长度

fileName = 'demo.txt'
with open(fileName,'w',encoding='utf-8') as f:
    f.write('hello,world\n')
    f.write('hello,world')
# 结果:12
#		11
fileName = 'demo.txt'
with open(fileName,'a',encoding='utf-8') as f:
    print(f.write('\n你好世界'))
# 结果:5

二进制文件

*eg:*将demo.mp3复制到新文件ABC.mp3。

fileName = r'C:\Users\Desktop\demo.mp3'	 # 此处r规避反斜杠\
with open(fileName,'rb') as f:
    # 新的文件名
    new_path = 'ABC.mp3'
    with open(new_path,'wb') as new_f:
        # 定义每次读取的大小
        c = 1024*100  # 二进制模式,它的基本单位不是字符,是字节
        # 1kb=1024byte  1mb=1024kb
        # 从旧对象中读取数据
        while True:
            content = f.read(c)
            # 如果数据没有了就退出
            if not content:
                break
            # 将读取到的数据写入到新的对象中
            new_f.write(content)
fileName = r'C:\Users\Desktop\demo.mp3'
with open(fileName,'rb') as f:
    new_path = 'ABC.mp3'
    # ABC.mp3里面添加两遍demo.mp3
    with open(new_path,'ab') as new_f:	# ab:追加
        c = 1024*100 
        while True:
            content = f.read(c)
            if not content:
                break
            new_f.write(content)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mport

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值