1.读文件

  • open:打开文件
  • read:读取文件
  • close:关闭文件
# 打开一个文件,指定文件路径,打开模式,编码方式, 返回一个文件对象
fd = open(file=r'C:\Users\11026\Desktop\test.txt', mode='r', encoding='utf-8')

# 读取文件的所有内容
# print(fd.read()) # hello world 你好,上海

# 指定读取文件内容的大小
# print(fd.read(9))  # hello wor

# 读取一行数据
# print(fd.readline())  # hello world

# 读取所有行数据,会包含着换行符
print(fd.readlines())

# 关闭文件
fd.close()

 

2.写文件

  • open:打开文件
  • write:写入文件
  • close:关闭文件
# 打开一个文件,指定文件路径,打开模式,编码方式, 返回一个文件对象
fd = open(file=r'C:\Users\11026\Desktop\test.txt', mode='wb', encoding='utf-8')

""" 写文件 """
fd.write('hello world'.encode('utf-8'))


# 文件关闭
fd.close()

 

3.文件的打开方式

python中文件的打开方式有多种组合,每个字符的意义如下

========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r'       open for reading (default)
'w'       open for writing, truncating the file first
'x'       create a new file and open it for writing
'a'       open for writing, appending to the end of the file if it exists

'b'       binary mode
't'       text mode (default)

'+'       open a disk file for updating (reading and writing)

The default mode is 'rt' (open for reading text).

常用的打开模式组合如下:

  • 只读:r,rt,rb (用)
    • 存在,读
    • 不存在,报错
  • 只写:w,wt,wb(用)
    • 存在,清空再写
    • 不存在,创建再写
  • 只写:a,at,ab【尾部追加】
    • 不存在,创建再写
    • 存在,尾部追加。
  • 只写:x,xt,xb
    • 存在,报错
    • 不存在,创建再写。
  • 读写
    • r+,rt+,rb+,默认光标位置:起始位置
    • w+,wt+,wb+,默认光标位置:起始位置(清空文件)
    • a+,at+,ab+,默认光标位置:末尾

4.使用上下文管理操作文件

之前对文件进行操作时,每次都要打开和关闭文件,比较繁琐且容易忘记关闭文件。

以后再进行文件操作时,推荐大家使用with上下文管理,它可以自动实现关闭文件。

 

with open("xxxx.txt", mode='rb') as file_object:
data = file_object.read()
print(data)

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open("xxxx.txt", mode='rb') as f1, open("xxxx.txt", mode='rb') as f2:
pass

 

思考:如果有一个100G的文件,该如何读取文件呢?

with open(file=r'C:\Users\11026\Desktop\test.txt', mode='r', encoding='utf-8') as fd:
    res = fd.read(1024)
    while res:
        print(res)
        # do something
        res = fd.read(1024)
posted on 2022-11-04 17:26  阿明明  阅读(117)  评论(0)    收藏  举报