不同的打开文件的方式
1…写数据(write) 如果文件不存在那么创建,如果存在那么就先清空,然后写入数据
(1).格式:
对象 = open(“文件”,w)
对象.write(“写入数据”)
对象.close
(2).案例:
f = open(‘test.txt’, ‘w’)
f.write(‘hello world, i am here!’)
f.close()
2.读数据(read)
如果用open打开文件时,如果使用的"r",那么可以省略,即只写 open(‘test.txt’)
如果没有文件,打开报错,存在该文件才能操作
如果文件中存在中文显示,会出现乱码需要添加encoding=‘utf-8’
open(‘test.txt’,”r”, encoding=‘utf-8’)
(1).格式:
对象 = open(“文件”,r)
变量 = 对象.read()
print(变量)
(2).案例
f = open(‘test.txt’, ‘r’)
content = f.read()
print(content)
3.读数据(readlines) 使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据
(1).格式:
对象 = open(“文件”,r)
变量 = 对象.readlines()
print(变量)
(2).案例:
f = open(‘test.txt’, ‘r’)
content = f.readlines()
print(content)
print(type(content))
4.读数据(readline)
Python文件的操作与异常处理
最新推荐文章于 2024-05-09 09:20:32 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)