文件三要素:
文件路径、编码方式、操作模式
读
r
read() : 全部内容
read(n):
在r模式下:字符
在rb模式下:字节
readline(): 按行读取
readlines(): ---> list 每个元素 都是文件中的每一行
r+
读写:先读写,后追加
rb
非文本文件,bytes类型
r+b
写
w
文件不存在,创建一个文件。
文件存在:将原文件内容清空。
w+
wb
w+b
追加
a
文件不存在,创建一个文件
文件存在:在最后直接追加
a+
ab
a+b
常用方法:
readable 是否可读
writable 是否可写
seek 移动光标 seek(0) : 将光标移动到文件开始 seek(0,2),将光标移动文件尾部
tell 告知光标的位置
truncate 截取
with open() as f1:
pass
with open('b',encoding='utf-8',mode='w+') as f2:
f2.write("这是我第一次写的数据
") # 写完以后,光标在文件最后
content = f2.read() # 所以读取不到任何内容
cursor = f2.tell() # 输出结果:32 单位是字节,可见写入文件时‘
’是两个字节
print(cursor)
print(content)
print(len('这是我第一次写的数据
')) # len()方法,对于字符串统计,统计的字符的个数,'
'转义字符,算一个统计
# with open('b',encoding='utf-8',mode='w+') as f3:
# f3.write("这是我第二次写文件数据
深圳分校骑士计划怎么样?
未来才知道。")
# f3.seek(0) # 将光标移动到文件的开始
# content = f3.read()
# print(content)
with open('b',encoding='utf-8',mode='r') as f:
# f.seek(0,2) # 因此,要记住 seek(0,2)就是将光标移动文件尾部
# print(f.tell()) # 输出光标的位置 91
f.read()
print(f.tell()) # 输出结果:91
文件操作案例:
# 文件内容如下:
# name:apple price:10 amount:3 year:2017
# name:tesla price:900 amount:9 year:2018
# name:desk price:90 amount:9 year:2018
# 将以上内容保存到一个文件,比如'c'上,最后,将文件读取出来
# 外理,转换为
'''name':'apple','price':10,'amount':3,'year':2017},
{name':'tesla','price':1000000,'amount':1,'year':2018}]
'''
# with open('c',encoding='utf-8',mode='r') as f:
# for line in f:
# if line: # 有可能文件最后一行,是空行,空行,也有
字符,所以这种方式 ,判断不行
# line_list = line.strip().split() # 通过对文件句柄 进行 for 循环,一行一行地读,行尾有
,所以strip()
# print(line_list)
# 以个输出结果为:
'''
['name:apple', 'price:10', 'amount:3', 'year:2017']
['name:tesla', 'price:900', 'amount:9', 'year:2018']
['name:desk', 'price:90', 'amount:9', 'year:2018']
'''
commodity_list = []
with open('c',encoding='utf-8',mode='r') as f1:
for line in f1:
line = line.strip() # 这行就OK了,先将只有
的行,变成空字符串
if line:
line_list = line.split()
print(line_list)
dic = {}
for e in line_list:
key,value = e.split(":") # 对字符串分割,得到列表
dic[key] = value
commodity_list.append(dic)
f1.close()
print(commodity_list)