文件操作
在实际操作中,通常需要将数据写入到本地文件或者从本地文件中读取数据等操作,那么作为Python爱好者的我们,必须掌握用Python语言对本地文件进行操作。
本地文件操作步骤
~找到文件所在位置
~打开文件
~操作文件
~关闭文件
open()函数
open函数语法
open(file,mode = ‘r’,encoding = None) --->打开文件
· file ---->文件路径
·mode ---->操作文件模式
~ r ---->只读模式
~ w ---->写入
~ a ---->追加
·encoding ---->指定文件编码
~utf-8 ---->当文件中文乱码时,则指定编码为utf-8解决
只读模式r
~f.readable() ---->判断是否可读
~f.read(n) ---->读取全部,在python3中n为字符
~f.readline() ---->逐行读取,包括\n
~f.readlines() ---->读取所有,返回值为列表,包括\n
练习:
f = open('test.txt', mode='r', encoding='utf-8') # 文件只读状态下,文件不存在----报错
# print((f.readable()) # 判断文件是否可读,返回值是bool
# print(f.read()) # 读取文件的全部内容
#
# print(f.read()) # 由于是指针读取,所有指针移动到最后一个,不能从头开始
# 只想要前3个字符
# print(f.read(6)) # 数字 , \n,汉字都是一个字符
# readline————读一行
# print(f.readline(),end='')
# print(f.readline())
# 查看文件指针的位置——tell
# print(f.tell()) # 0 查看当前文件所处文件的位置,返回的是字节
# print(f.readline(),end='')
# print(f.tell()) # 字母,数字代表一个字节\n2个字节 汉子3个字节
#seek
'''
whence:0(从头开始读取) 1(当前指针位置) 2(文件尾)
offset:偏移量
'''
# print(f.tell())
# f.seek(2,0)
# print(f.tell())
# print(f.read())
print(f.readline()[0]) # list根据索引获取值
只写模式w
#文件只写状态下,文件不存在----不报错,会自动创建文件
f = open('test.txt', mode='w', encoding='utf-8')
#print(f.writable()) # 判断是否可写
f.write('hello world') # 在w模式下,重新写入内容,会覆盖了
#print(f.write('hello world')) #11个字符
#writerlines
f.writelines({'第一行\n','第二行\n'}) #{a,b,c}---无序
追加a
# a 追加 文件不存在---不会报错,会主动创建
f = open('test.txt', mode='a', encoding='utf-8')
f.write('hello world\n')
f.write('nihao\n') #在原来的位置上追加
混合模式
# r+ 可读可写,以读为主
# f = open('test.txt', mode='r+', encoding='utf-8')
# #print(f.read())
# f.write('你好') # 根据长度覆盖
# print(f.read())
f = open('test.txt', mode='r+', encoding='utf-8')
f.write('hello world')
f.seek(0)
print(f.read())
print(f.readline())
json模式
# b = b'hello world' # 字节
# f = open('test1.txt', 'wb')
# f.write(b)
# w模式下写入的类型必须是str
'''
json.dump() 将python对象转为json对象 文件
json.load() 将json对象转为python对象 文件
字典:key--value
'''
# import json
#
# data = {"name": "zs"} # 字典
# f = open('data.json', 'w')
# # f.write(data) dict , 只能写入字符串 json数据究其本质是str
# json.dump(data, f) # dict ---- json(str)
import json
f = open('data.json','r')
# res = f.read()
# print(type(res))
j_data = json.load(f)
print(j_data)
print(j_data['name'])
文件关闭
import time
'''
写入其他代码--其他代码报错--文件没有及时close--文件内容还在吗?能成功写入吗?
'''
f = open('test3.txt','w')
f.write('hello')
time.sleep(2)
f.close() # 如果文件没有关闭,会一直停留在内存中,文件关闭之后,才会真正写入到硬盘
# 异常处理
try:
f = open('test3.txt','w')
f.write('hello')
print("很多代码")
except:
pass
finally:
if f: # 前提必须有文件对象,才能执行文件相应的方法
f.close()
withopen方法
'''
不需要f.close()语句
'''
import time
with open('test5.txt','w') as f_obj:
f_obj.write('aaa')
time.sleep(5)
print('hello')