侧边栏壁纸
  • 累计撰写 197 篇文章
  • 累计收到 496 条评论

Python学习笔记之文件操作

2019-9-22 / 0 评论 / 57 阅读
# 文件操作
'''
 w write 写入模式
    文件不存在则创建文件,如果文件存在则清空文件,并将指针置于文件开头

 r read 读取模式
    文件不存在则报错,如果文件存在打开文件并将指针置于文件开头

 a append 追加默认
    文件不存在则创建文件,如果文件存在则打开文件,并将指针置于文件开头

 x xor 异或默模式
    文件已存在则报错,不存在则创建文件,将文件指针置于文件开头

# 扩展模式
    + plus 可以让文件具有读写功能
    b bytes (bytes模式)二进制字节流

# 模式一共16种
    w, w+, wb, wb+
    r, r+, rb, rb+
    a, a+, ab, ab+
    x, x+, xb, xb+

# encoding = 'utf-8' 不能写在二进制字节流模式
'''

# 写操作
# 使用write模式 对 zhangyutong.text 文件进行打开
fp = open('zhangyutong.text','w')
# 在里面写一段话
fp.write('张宇童 - 前沿技术博客')
# 关闭文件
fp.close() # 张宇童 - 前沿技术博客

# 使用read打开 zhangyutong.text 文件
fp = open('zhangyutong.text','r')
res = fp.read()
print(res) # 张宇童 - 前沿技术博客

# 使用append打开 zhangyutong.text 文件
fp = open('zhangyutong.text', 'a')
fp.write('---温馨技术博客')
fp.close()

# 使用xor打开 zhangyutong.text 文件
# fp = open('zhangyutong2.text', 'x')
# fp.write('hello')
# fp.close()

# 将字符串和字节流之间转换
# encode() 编码
# decode() 解码

# 打开文件操作
fp = open('zhangyutong.text','rb')
res = fp.read()
fp.close()
print(res.decode('utf-8'))

fp = open('zhangyutong.text', 'wb')
fp.write('你好张宇童'.encode('utf-8'))
fp.close()

# utf-8一个中文汉字 占用 三个字节
# read() 读取字符的个数,里面的参数表示字符的个数
# seek() 调整指针的位置,里面的参数代表字符的个数
# tell() 返回指针的位置,
fp = open('zhangyutong.text','a+')
fp.seek(3)
res = fp.read()
r = fp.tell()
fp.close() 
print(res) # 你好世界

# 刷新缓冲区flush触发时机
# 作用:迅速将缓冲区里面的内容写到文件内部
# 1、当文件关闭的时候自动刷新缓冲区
# 2、当整个程序运行完毕时自动刷新缓冲区
# 3、当缓冲区写满时自动刷新缓冲区
# 4、手动刷新缓冲区

# fp = open('blog.txt','a+', encoding='utf-8')
# fp.write('hello ni haõ')
# fp.flush()
# fp.close()

# with语法 会自动的close文件,as右侧 用于接受open句柄
with open('blog.txt', 'r+', encoding='utf-8') as fp:
    res = fp.read()
    print(res) # hello ni haõhello

# 文件相关函数
'''
readline()
功能: 用于读取一行文件的内容
readlines()
功能: 将文件中的内容按换行读取到list里面
writelines()
功能: 将内容时字符串的可迭代数据写到文件中 
参数: 内容为字符串的可迭代数据
truncate
功能: 把要截取的字符串提取出来,清空文件内容,重新写入(字节)

'''
print('========><========')
# 使用readline读出文件所有内容
with open('blog.txt', 'r+', encoding= 'utf-8') as fp:
    res = fp.readline()
    while res:
        print(res, end='')
        res = fp.readline()

with open('blog.txt', 'r+', encoding= 'utf-8') as fp:
    res = fp.readline(2)
    print(res) # 白日
    res = fp.readline(2)
    print(res) # 依山
    res = fp.readline(2)
    print(res) # 尽

print('========>readlines<========')
with open('blog.txt', 'r+', encoding='utf-8') as fp:
    res = fp.readlines()
    res = {i:k.strip() for i,k in enumerate(res)}
    print(res)

print('==========>writeline<===========')
with open('blog.txt', 'a+', encoding='utf-8') as fp:
    strvar = '春眠不觉晓'
    fp.writelines(strvar)
    listvar = ['\n唧唧复唧唧歪\n','木兰当户织']
    fp.writelines(listvar)
    fp.writelines(map(str, range(6)))

print('==========>truncate<==========')
with open('blog.txt', 'r+', encoding='utf-8') as fp:
    fp.truncate(10)

评论一下?

OωO
取消