# 能调用方法的一定是对象,文件也是对象
# file = open('C:/Users/qwer/Desktop/python.txt', 'r')
# # r是读操作,不能调取写方法 w是写操作,不能调取读方法,先清空再写,没有文件先创建文件 a是在内容末尾光标处追击内容
# print(file.read())
# print(file.read(5)) # 能取到一个字符,一个汉字就是一个字符
# file.close()
# clear_file = open('C:/Users/qwer/Desktop/yzy.txt', 'w')
# clear_file.write('aaaaaaaaaaaaaaaaaaaaaa\n')
# clear_file.write('gggggggggggggg')
# # 这样写不会后面的覆盖前面的
# clear_file.close()
# append_file = open('C:/Users/qwer/Desktop/yzy.txt', 'a')
# append_file.write('\n心灵鸡*汤') # 这句是把内容放到缓冲区,到了close的时候才存到磁盘中
# time.sleep(10) # 类似于js中的setTimeout,多久之后才执行后面的语句,需要引入time包
# append_file.close() # 将缓冲区的数据写到磁盘
# new_file = open('C:/Users/qwer/Desktop/yzy.txt', 'r')
# print(new_file.read())
# new_file.close()
# 文件操作方法
action_file = open('C:/Users/qwer/Desktop/python.txt', 'r')
# print(action_file.read(5)) # 读到哪光标移到了哪,读时候从光标位置开始读
# print(action_file.readline())
# print(action_file.readlines()) # 返回一个列表
# number = 0
# for i in action_file.readlines(): # 文件写到了内存中
# number += 1
# if number == 3:
# i = i.strip() + 'hello'
# i = ''.join([i.strip(), 'hello']) # 优化字符串拼接
# print(i.strip()) # print会有默认的换行,用strip清除行行之间的换行
# action_file.close()
# 最优方法
# number = 0
# for i in action_file: # 文件仍然在磁盘中,此时action_file是个迭代器,推荐使用的方式
# number += 1
# if number == 2:
# i = ''.join([i.strip(), 'hello'])
# print(i.strip())
# print(action_file.read(10))
# print(action_file.tell()) # 显示当前光标的位置,英文一个字符,中文一个字是三个字符
# print(action_file.seek(0)) # 重新调整光标位置
# print(action_file.tell())
# action_file = open('C:/Users/qwer/Desktop/python.txt', 'r')
# action_file.truncate(2) # 从光标位置截断文件内容,若光标在开始位置,相当于将此文件清空, w的时候好用,a时候不报错,但也没效果
# 终端进度条效果
# import sys, time
# for i in range(30):
# # print('*', end='', flush=True) # 打印不换行,这一句等价于下面两句话
# sys.stdout.write('*')
# sys.stdout.flush()
# time.sleep(0.1) # 这里的实际间隔时间是0.2*30
# print(action_file.isatty()) # 判断是不是终端,返回布尔值
# 操作文件的模式
# w: 写模式
# r: 读模式
# a: 追加模式
# r+: 读写模式 读正常 写在最后写 光标在起始位置 (最常用)
# w+: 写读模式 先清空已有内容,写了之后再读还是读不到,写完了光标在写完了的位置 所以接下来读不到内容 想看到所有内容 需要调整光标
# a+: 追加读模式 模式决定了光标在最后 所以上来就读 读不到内容
# f = open('C:/Users/qwer/Desktop/yzy.txt', 'a+')
# print(f.readline())
# print(f.tell())
# f.write('哈哈哈')
# print(f.seek(0))
# print(f.readline())
# f.close()
# 修改磁盘文件
# f_read = open('C:/Users/qwer/Desktop/yzy.txt', 'r')
# f_write = open('C:/Users/qwer/Desktop/yzy_tengxi.txt', 'w')
# number = 0
# for i in f_read:
# number += 1
# if number == 2:
# i = '\nthis is a new line \n \n'
# f_write.write(i)
# f_read.close()
# f_write.close()
# with 语句 省略了close语句 推荐用法
# with open ('C:/Users/qwer/Desktop/yzy.txt', 'r') as with_file:
# print(with_file.read())
# 同时创建多个文件对象
# with open('C:/Users/qwer/Desktop/yzy.txt', 'r') as read_file, open('C:/Users/qwer/Desktop/yzy_tengxi.txt', 'w') as write_file:
# for line in read_file:
# write_file.write(line)