文件

本文详细介绍了文件操作的相关知识,包括如何打开、关闭文件,以及读取大文件的策略。同时讲解了文本和二进制文件的读写方法,如read(), readline(), readlines()以及write()。此外,还涵盖了文件位置的改变(seek())和当前位置的查询(tell())。文章最后提到了一些文件的其他操作,如目录管理和文件的删除、重命名。
摘要由CSDN通过智能技术生成

打开文件

使用open函数来打开一个文件
参数:file ,要打开的文件的名字(路径)
返回值:返回一个对象,这个对象代表当前打开的文件

在这里插入图片描述

文件关闭

调用close() 方法来关闭文件

file_name = 'demo.txt'
file_obj = open(file_name)
# 关闭文件
file_obj.close()

with … as 语句

file_name = 'demo.txt'
try:
    with open(file_name) as file_obj:
        print(file_obj.read())
except :
    print(f'{file_name} 文件不存在')

with语句中可以直接使用file_obj来做文件操作,此时‘demo.txt’这个文件只能在with中使用,一旦with结束则文件会自动close。

文件读取

调用 open() 来打开一个文件,可以将文件分成两种类型

  1. 纯文本文件(使用 utf-8 等编码编写的文本文件)
  2. 二进制文件(图片、mp3、ppt等这些文件)
  • open() 打开文件时,默认以文本文件的形式打开,但是默认的编码为None。所以处理文本文件时,必须指定文件的编码。

read() :读取文件内容

通过 read() 读取文件内容时,如果直接调用 read() 它会将文本文件的所有内容全部都读取出来。如果要读取的文件较大的话,会一次性将文件的内容加载到内存中,容易导致内存泄漏。所以对于较大的文件,不要直接调用read()

  • read() 可以接收一个size作为参数,该参数用来指定要读取的字符的数量。
  1. 默认值为-1,它会读取文件中的所有字符
  2. 可以为size指定一个值,这样read()会读取指定数量的字符。每一次读取都会被记录,所以下一次读取会从上次读取结束为止开始读取。
  3. 如果字符的数量小于size,则会读取剩下所有内容。如果已经读取到了文件最后,则会返回 ‘ ’ 空串。
  • readline():读取一行的内容
  • readlines() :该方法用于一行一行的读取内容,它会一次性将读取到的内容封装到一个列表中返回

读取大文件的方式

# 读取大文件的方式
file_name = 'demo.txt'
try:
    with open(file_name,encoding='utf-8') as file_obj:
        # 定义一个变量,来保存文件的内容
        file_content = ''
        # 定义一个变量来指定每次读取的大小
        chunk = 100
        # 创建一个循环来读取文件的内容
        while True :
            # 读取chunk大小的内容
            content = file_obj.read(chunk)

            # 检查是否读取到了内容
            if not content :
                # 内容读取完毕,退出循环
                break
            file_content += content

except FileNotFoundError:
    print(f'{file_name} 这个文件不存在')

print(file_content)

demo.txt

College students need to take part in the social practice before they graduate, many universities encourage students to do it, they have some policies to support students to carry on social practice. It is obvious that social practice is very important for college students, students can gain a lot from it.First, students can contact to the real world, they can learn to deal with the things which they will meet in the future. Students always keep their study in the campus, what they have learned is from the book, but they don’t have the chance to practice it, social practice provides them the chance. Students can make their knowledge useful.Second, social practice is very helpful in finding jobs for students. When students come to the job market, the employers pay special attention to the working experience, social practice belongs to it, it helps students stand out and win the chance to take the job interview. The employers think you can handle some situations because of your social practice.There is no doubt that students should join the social practice, it is very useful to help students in improving their ability and gaining the job interview.

文件写入

  • 使用 open() 打开文件时必须要指定打开文件所要做的操作(读、写、追加),如果不指定操作类型,则默认是读取文件,而读取文件时是不能向文件中写入的。

  • 使用 open() 时向其添加指定参数可以获得指定功能

  • ‘r’ :表示只读

  • ‘w’:表示是可写的,使用’w’参数来写入文件时,如果文件不存在会创建文件,如果文件存在则会截断文件(指删除原来文件中的所有内容)

  • ‘a’:表示追加内容,如果文件不存在则会创建文件,如果文件存在则会向文件中追加内容

  • ‘x’:用来新建文件,如果文件不存在则创建,存在则报错

‘+’可以为操作符增加功能

  • ‘r+’:既可读又可写,文件不存在会报错

write() 用来向文件中写入内容。如果操作的是一个文本文件的话,则write() 需要传递一个字符串作为参数。该方法会分多次向文件中写入内容,写入完成以后,该方法会返回写入的字符的个数。

file_name = 'demo.txt'

with open(file_name,'w',encoding='utf-8') as file_obj:
    file_obj.write('aaa\n')
    file_obj.write('bbb\n')
    file_obj.write('ccc\n')
    r = file_obj.write(str(123) + '123123\n')
    print(r)

二进制文件

读取模式
t 读取文本文件(默认值)
b 读取二进制文件

读取文本文件是,size是以字符为单位的;读取二进制文件时,size以字节为单位。

file_name = 'C:/Users/Administrator/Desktop/timg.jpg'

# 读文件
with open(file_name,'rb') as file_obj:
    
    # 定义一个新的文件,将读取的内容写入
    new_name = 'beauty.jpg'
    with open(new_name,'wb') as new_obj:
        # 定义每次读取的大小
        chunk = 1024 * 1024
         
        while True:
            # 从已有的对象中读取数据
            content = file_obj.read(chunk)

            # 内容读取完毕,终止循环
            if not content:
                break
            # 将读取到的数据写入到新对象中
            new_obj.write(content)

读取文件的位置

  • seek() :可以修改当前读取的位置

seek()需要两个参数:
1.要切换到的位置
2.计算位置方式(可选值:0、1、2)

0 : 从头计算(默认)
1 : 从当前位置计算
2 : 从最后位置开始计算

  • tell() :查看当前读取的位置

文件的其他操作

os.listdir() :获取指定目录的目录结果

os.getcwd() :获取当前所在的目录

os.chdir() :切换当前所在的目录

os.mkdir(“xxx”) :在当前目录下创建一个名字为xxx的目录

os.rmdir() :删除目录

os.remove() :删除文件

os.rename() :可以对一个文件进行重命名,也可以用来移动一个文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值