python open read write读写操作参数实验

小白日记

本文记录open read write函数各个参数产生的效果

新建一个空文件夹和一个空py

在这里插入图片描述

直接open

with open('abc.txt') as f:
    pass
Exception has occurred: FileNotFoundError
[Errno 2] No such file or directory: 'abc.txt'
  File "D:\Desktop\test\test.py", line 1, in <module>
    with open('abc.txt') as f:

加w参数

with open('abc.txt', 'w') as f:
    pass

创建了abc.txt

如果abc已存在,并里面有内容

在这里插入图片描述
再次运行

with open('abc.txt', 'w') as f:
    pass

abc.txt被清空。

x参数

此时abc.txt存在,运行以下代码

with open('abc.txt', 'x') as f:
    pass

报错,已存在x

Exception has occurred: FileExistsError
[Errno 17] File exists: 'abc.txt'
  File "D:\Desktop\test\test.py", line 1, in <module>
    with open('abc.txt', 'x') as f:

w和w+

现在在abc中输入内容,
在这里插入图片描述
并运行以下代码

with open('abc.txt', 'w') as f:
    print(f.read())

报错,不可读

Exception has occurred: UnsupportedOperation
not readable
  File "D:\Desktop\test\test.py", line 2, in <module>
    print(f.read())

但值得注意的是,此时abc.txt已经被清空。
此时在abc.txt中再输入内容
并运行以下代码

with open('abc.txt', 'w+') as f:
    print(f.read())

abc.txt被清空,并输出空

r和r+

修改abc如下
在这里插入图片描述
运行以下代码

with open('abc.txt', 'r') as f:
    print(f.read())

输出完整的abc.txt如下

0000000000000000000000
00000000000000
000000000
0000

运行以下代码

with open('abc.txt', 'r+') as f:
    print(f.read())
    f.write('1')

此时abc.txt如下,在末尾添加了1

0000000000000000000000
00000000000000
000000000
00001

运行以下代码

with open('abc.txt', 'r+') as f:
    f.write('1')

此时abc.txt如下,开头的0被“覆盖”成1

1000000000000000000000
00000000000000
000000000
00001

总结

open函数返回一个<class '_io.TextIOWrapper'>
而read函数会将读写指针从开头移动到末尾,在这个过程读取每个字符并记录下来,返回<class 'str'>
write是在指针所在位置后插入字符。

参数 读写 open后指针位置 效果
x 仅写 开头 创建文件,不支持读,若文件存在则报错,基本不用
x+ 可写,可读(但无效) 开头 创建文件并可读,但因为文件刚创建所以读出来一定是空,基本不用
w 仅写 开头 文件不存在则创建文件,文件存在则清空内容,简单理解就是创建并覆盖,不支持读
w+ 可写,可读(但无效) 开头 创建并覆盖,可读,但读出来一定是空。因为文件已清空
a 仅写 末尾 a打开后指针已经在最后,写在原本内容最后
a+ 可写,可读(但无效) 末尾 读出来一定是空,因为a+打开后指针已经在最后
r 仅读 开头 指针在最开头,
r+ 可写,可读 开头 写入会覆盖第一个、第二个…字符,直接读和无参数或‘t’参数效果一样

生产实践

创建文件\覆盖原文件并写入

直接无脑w参数
个人认为w+没有存在的意义,但若要细究w和w+的区别,可以参见Python w和w+权限的区别

读取已存在文件内容

不写参数、参数t、参数r

在文末写入

r+

文件若存在就从后面写入,不存在就创建文件。

只能通过os.path.exists()来判断是否存在,然后采用上述两种方法。

猜你喜欢

转载自blog.csdn.net/weixin_45518621/article/details/129728101
今日推荐