day8 文件操作

#!/usr/bin/env python 
# -*- coding:utf-8 -*-

# 绝对路径的文件
# T_file = open('d:\江豚.txt', mode='r', encoding='gbk')
# content = T_file.read()
# print(content)
# T_file.close()

# open操作封装了 bytes ---> str 的操作
# tF = open('Playboy.txt', mode='r', encoding='utf-8')
# content = tF.read()
# print(content)
# tF.close()

# rb 以bytes文件类型读取,用在非文字类型文件的读取
# tF = open('Playboy.txt', mode='rb',)
# content = tF.read()
# print(content)
# tF.close()

# 读写
# f = open('log', mode='r+', encoding='utf-8')
# content = f.read()
# print(content)
# f.write(' ,三九是天')
# # 读写操作添加后的内容,不会更新
# print(content)
# f.close()

# f = open('log', mode='r+', encoding='utf-8')
# f.write('aaa')
# # 读的是原来没有被write操作覆盖掉的部分
# print(f.read())
# f.close()

# f = open('log', mode='r+b')
# print(f.read())
# f.write(',非强'.encode('utf-8'))
# f.close()

# 写入
# 对于,w;如果没有此文件就创建文件,如果有就全部重新覆盖
# tF = open('log', mode='w', encoding='utf-8')
# content = tF.write('HD,DP')
# tF.close()

# f = open('log', mode='w+', encoding='utf-8')
# f.write('aa')
# f.seek(0)
# # seek定位光标,read方法是读光标后的所有内容
# print(f.read())
# f.close()

# tF = open('log', mode='w', encoding='utf-8')
# content = tF.write('高清 ,显示')
# tF.close()

# 以bytes形式写入文件,encode方式要符合文件的编码方式
# tF = open('log', mode='wb', )
# content = tF.write('高清 ,显示'.encode('utf-8'))
# tF.close()

# 追加
# f = open('log', mode='a', encoding='utf-8')
# f.write(' ,这是追加的内容')
# f.close()

# f = open('log', mode='ab',)
# f.write(' ,这是追加的内容'.encode('utf-8'))
# f.close()

# f = open('log', mode='a+', encoding='utf-8')
# f.write(' ,这是追加的内容')
# f.seek(0)
# print(f.read())
# f.close()

# f = open('log', mode='ab')
# f.write(' ,这是追加的内容'.encode('utf-8'))
# f.close()

# 功能详解
# f = open('log', mode='r+', encoding='utf-8')
# content = f.read(3) # ()内是指定的,读出的字符数
# f.seek(3) # 光标读出来的是比特位,读出来的字节
# tell()告诉光标当前位置
# print(f.tell())
# content = f.read()
# print(content)
# f.tell()
# f.readable() # 是否可读
# line = f.readline() # 一行一行的读
# line = f.readlines() # 每一行当成列表的中的一个元素,添加到展示列表
# f.truncate(5)
# 用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。
# 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。

# 读取文件,{有节制的读,确定读取范围}
# for line in f:
#     print(line)
# f.close()


# f = open('log', mode='a+', encoding='utf-8')
# f.write('佳琦')
# count = f.tell()
# f.seek(count - 9)
# print(f.read())
# f.close()

# 自动关闭及不需要手动写close(),第二种打开文件方式
# with open('log', mode='r+', encoding='utf-8') as f, \
#         open('log', mode='r+', encoding='utf-8') as f1:
#     print(f.read())

 

posted @ 2019-02-26 22:43  云川望雨  阅读(103)  评论(0编辑  收藏  举报