Python-学习之路-13 file 文件

2019-02-26  本文已影响0人  末世狂人

文件

open 函数

# 打开文件,用写的形式
# f称之为文件句柄
f = open("test01.txt",'w')
#文件打开之后必须关闭
f.close()

with 语句

# with语句案例
with open(r"test01.txt",'r') as f1:
    # 按行读取内容
    strline = f1.readline()
    # 这种结构能够保证完整的读取文件直到结尾
    while strline:  
        print(strline)
        strline = f1.readline()
        
print("方法二")        
    
with open(r"test01.txt",'r') as f2:      
    # 全部读取(如果文件过大,不推荐此方法)
    strlines = f2.readlines()
    for sl in strlines:
        print(sl)
人生若只如初见

何事秋风悲画扇

等闲变却故人心

却道故人心易变

方法二
人生若只如初见

何事秋风悲画扇

等闲变却故人心

却道故人心易变
# read 按字符读取文件内容
# 允许输入参数巨鼎读取机制字符,如果没有制定,从当前位置读取到结尾
# 否则.从当前位置读取到指定个数字符

with open(r'test01.txt','r') as f:
    strChar = f.read(7)
    print(strChar)
人生若只如初见
with open(r'test01.txt','r') as f:
    strChar = f.read(1)
    while strChar:
        print(strChar,end = "")
        strChar = f.read(1)
人生若只如初见
何事秋风悲画扇
等闲变却故人心
却道故人心易变

seek (offset,from)

# seek 案例
# 打开问价后,从第五个字节开始读取
with open(r'test01.txt','r') as f:
    f.seek(6,0)
    strChar = f.read()
    print(strChar)
若只如初见
何事秋风悲画扇
等闲变却故人心
却道故人心易变

tell 函数

# tell
with open(r'test01.txt','r') as f:
    strChar = f.read(7)
    index = f.tell()
    while strChar:
        print(index)
        print(strChar)
        strChar = f.read(8)
        index = f.tell()
21
人生若只如初见
43

何事秋风悲画扇
65

等闲变却故人心
87

却道故人心易变
88

write 文件的写操作

# write 案例
with open(r'test01.txt','w') as f:
    f.write("昨夜雨疏风骤, \n浓睡不消残酒")
    # 需手动添加换行符
    strList = ["试问卷帘人\n","却道海棠依旧\n","知否知否\n","应是绿肥红瘦"]
    f.writelines(strList)

pickle 持久化

shelve 持久化工具

# shelve案例
import shelve

#写入
shv = shelve.open(r'shv.db')
shv['one'] = 1
shv['tow'] = 2
shv['three'] = 3
shv.close()

# 读取
shv = shelve.open(r'shv.db')
print(shv["one"])
print(shv["tow"])
print(shv["three"])
1
2
3
上一篇 下一篇

猜你喜欢

热点阅读