文件(File)(Python入门三十九)

目录

打开文件

文件的读取

      读取大文件的方式

文件的写入

关闭文件


文件(File)


    - 通过Python程序来对计算机中的各种文件进行增删改查的操作
    - I/O(Input / Output)
    - 操作文件的步骤:
        ① 打开文件
        ② 对文件进行各种操作(读、写),然后保存
        ③ 关闭文件

file_name = 'c:/Users/lilichao/Desktop/告白气球.flac'

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

with open(file_name , 'rb') as file_obj:
    # 读取文本文件时,size是以字符为单位的
    # 读取二进制文件时,size是以字节为单位
    # print(file_obj.read(100))

    # 将读取到的内容写出来
    # 定义一个新的文件
    new_name = 'aa.flac'

    with open(new_name , 'wb') as new_obj:

        # 定义每次读取的大小
        chunk = 1024 * 100

        while True :
            # 从已有的对象中读取数据
            content = file_obj.read(chunk)

            # 内容读取完毕,终止循环
            if not content :
                break

            # 将读取到的数据写入到新对象中
            new_obj.write(content)

打开文件

open(file, mode='r', buffering=-1, encoding_=None, errors=None, newline=None, closefd=True, opener=None)
    - 使用open函数来打开一个文件
    - 参数:
       file 要打开的文件的名字(路径)
      返回值:
       返回一个对象,这个对象就代表了当前打开的文件

    - 创建一个变量,来保存文件的名字
       如果目标文件和当前文件在同一级目录下,则直接使用文件名即可
file_name = 'demo.txt'

    - 在windows系统使用路径时,可以使用/来代替 \
       或者可以使用 \\ 来代替 \
       或者也可以使用原始字符串
file_name = 'hello\\demo.txt'
file_name = r'hello\demo.txt'

    - 表示路径,可以使用..来返回一级目录
file_name = '../hello/demo.txt'

    - 如果目标文件距离当前文件比较远,此时可以使用绝对路径
       绝对路径应该从磁盘的根目录开始书写
file_name = r'C:\Users\lilichao\Desktop\hello.txt'

file_obj = open(file_name) # 打开 file_name 对应的文件

print(file_obj)

文件的读取

file_name = 'demo2.txt'

try:
    # 调用open()来打开一个文件,可以将文件分成两种类型
    # 一种,是纯文本文件(使用utf-8等编码编写的文本文件)
    # 一种,是二进制文件(图片、mp3、ppt等这些文件)
    # open()打开文件时,默认是以文本文件的形式打开的,但是open()默认的编码为None
    #   所以处理文本文件时,必须要指定文件的编码
    with open(file_name,encoding='utf-8') as file_obj:
        # 通过 read() 来读取文件中的内容
        # 如果直接调用read()它会将文本文件的所有内容全部都读取出来
        #   如果要读取的文件较大的话,会一次性将文件的内容加载到内存中,容易导致内存泄漏
        #   所以对于较大的文件,不要直接调用read()
        # help(file_obj.read)
        # read()可以接收一个size作为参数,该参数用来指定要读取的字符的数量
        #   默认值为-1,它会读取文件中的所有字符
        #   可以为size指定一个值,这样read()会读取指定数量的字符,
        #       每一次读取都是从上次读取到位置开始读取的
        #       如果字符的数量小于size,则会读取剩余所有的
        #       如果已经读取到了文件的最后了,则会返回''空串
        # content = file_obj.read(-1)
        content = file_obj.read(6)
        content = file_obj.read(6)
        content = file_obj.read(6)
        content = file_obj.read(6)
        # print(content)
        # print(len(content))
except FileNotFoundError :
    print(f'{file_name} 这个文件不存在!')

读取大文件的方式

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

            # 输出内容
            # print(content,end='')
            file_content += content

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


print(file_content)例子:

import pprint
import os
file_name = 'demo.txt'

with open(file_name , encoding='utf-8') as file_obj:
       readline()
       该方法可以用来读取一行内容
       print(file_obj.readline(),end='')
       print(file_obj.readline())
       print(file_obj.readline())

       readlines()
       该方法用于一行一行的读取内容,它会一次性将读取到的内容封装到一个列表中返回
       r = file_obj.readlines()
       pprint.pprint(r[0])
       pprint.pprint(r[1])
       pprint.pprint(r[2])

    for t in file_obj:
        print(t)

文件的写入

#open(file, mode='r', buffering=-1, encoding_=None, errors=None, newline=None, closefd=True, opener=None)

file_name = 'demo5.txt'

# 使用open()打开文件时必须要指定打开文件所要做的操作(读、写、追加)
# 如果不指定操作类型,则默认是 读取文件 , 而读取文件时是不能向文件中写入的
# r 表示只读的(看文件写入下面的open中的mode='r')
# w 表示是可写的,使用w来写入文件时,如果文件不存在会创建文件,如果文件存在则会截断文件
#   截断文件指删除原来文件中的所有内容
# a 表示追加内容,如果文件不存在会创建文件,如果文件存在则会向文件中追加内容
# x 用来新建文件,如果文件不存在则创建,存在则报错
# + 为操作符增加功能
#   r+ 即可读又可写,文件不存在会报错
#   w+
#   a+
with open(file_name , 'w' , encoding='utf-8') as file_obj:
with open(file_name , 'r+' , encoding='utf-8') as file_obj:
with open(file_name , 'x' , encoding='utf-8') as file_obj:

- write()来向文件中写入内容,
    # 如果操作的是一个文本文件的话,则write()需要传递一个字符串作为参数
    # 该方法会可以分多次向文件中写入内容
    # 写入完成以后,该方法会返回写入的字符的个数
    file_obj.write('aaa\n')
    file_obj.write('bbb\n')
    file_obj.write('ccc\n')
    r = file_obj.write(str(123)+'123123\n')
    r = file_obj.write('今天天气真不错')
    print(r)

关闭文件

    - 打开文件
file_name = 'demo.txt'

    - 调用open()来打开文件
# file_obj = open(file_name)

    - 当我们获取了文件对象以后,所有的对文件的操作都应该通过对象来进行
    - 读取文件中的内容
       read()方法,用来读取文件中的内容,它会将内容全部保存为一个字符串返回
content = file_obj.read()

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

    - with ... as 语句
      with open(file_name) as file_obj :
         # 在with语句中可以直接使用file_obj来做文件操作
         # 此时这个文件只能在with中使用,一旦with结束则文件会自动close()
           print(file_obj.read())


file_name = 'hello'

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小肝帝!

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

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

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

打赏作者

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

抵扣说明:

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

余额充值