python自学成才之路 文件读写操作

时间:2022-07-23
本文章向大家介绍python自学成才之路 文件读写操作,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

IO操作格式

python对文件IO操作有两种格式,第一种是如下形式:

filepath = 'IOtest.txt'
try:
    f = open(filepath,'r')
    print(f.read())
finally:
    if f:
        f.close()

第二种是如下形式:

filepath = 'IOtest.txt'
with open(filepath,'r') as f:
    print(f.read())

第二种方式可以理解为第一种方式的缩减版,第一种方式需要显示的调用close来关闭IO流,第二种方式with会自动关闭IO流。推荐使用第二种方式。

open函数的第一个参数是文件路径,第二个参数时IO模式,r表示只读,w表示写操作(写之前会清空文件内容),a表示追加操作(不会清空文件内容)。在r模式下不能写,在w模式些不能读,如果想同时能够执行读写操作可以使用r+模式,r+模式下可读写,且写是追加模式写。

读操作

文件对象读操作有一下几种方法: read():一次性读入整个文件内容 readline():读取一行文件内容 readlines():读取整个文件内容,并返回按行划分的文件内容列表 例如有一个IO.txt文件,内容如下:

hello world
hello world2
hello world4
filepath = 'IOtest.txt'
# 使用readline会逐行读取
with open(filepath,'r') as f:
    print(f.readline().strip())
    print(f.readline().strip())
输出:
hello world
hello world2

# 使用read会一次性全读取出来
with open(filepath,'r') as f:
    print(f.read())

# 使用readlines会先返回文件内容列表,将内容先存放到lines中,即使文件IO关闭了,内容还能读取
with open(filepath,'r') as f:
    lines = f.readlines()
for line in lines:
    print(line.strip())

# 如果要逐行读取,直接遍历文件对象就可以了
with open(filepath,'r') as f:
    for line in f:
        print(line.strip())

写操作

# 使用a模式表示追加,使用w则表示覆盖写
with open(filepath,'a') as f:
    f.write("hello world")