#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
f=open("test_1",'r',encoding="utf-8") #'r'代表读文件
'''
#----------读文件----------
print(f.tell()) #tell计数按照字符来计数
print(f.read(5)) #读前5个字符,注意此时文件指针已经到第5个
print(f.tell())
data=f.readline() #读取下一行
print(data)
print(f.tell())
f.seek(10) #文件指针指向指定的值(即第几个字符)
print(f.readline())
print(f.tell())
#----------刷新---------- #装逼方法
import sys,time
for i in range(20):
sys.stdout.write("#")
sys.stdout.flush()
time.sleep(0.1)
#----------写文件----------
f1=open("test_2",'w',encoding="utf-8")#'w'代表写文件
f1.write("hello") # 注:若test_2文件已存在,那么调用f2.write()方法会将test_2文件中的内容覆盖掉
#但 若test_2文件不存在,那么write()方法会创建一个新文件
f2=open("test_2",'a',encoding="utf-8") #f2是文件句柄,'a'代表append,即追加且不覆盖原文件内容,但不可读
# 'a+'代表追加读写,即追加且不覆盖源文件内容,可读
f2.write("我爱北京天安门...\n")
f2.write("天安门上太阳升\n")
#----------读取文件指定行数---------
for i in range(5): #读取文件前5行
print(f.readline()) #readline():读取文件的下一行
#----------遍历文件----------
#---low的写法---
for index,line in enumerate(f.readlines()): #f.readlines():将文件的每行作为一个元素,存入列表中
# 注:readlines()只适合读小文件,因为需要将文件作为一个列表放到
# 内存中
if index==9: #enumerate:将行标取出
print("---------------")
print(line.strip()) #去除列表元素中的空格以及换行
#---高大上的写法---
count=0
for line in f:
print(line.strip())
count+=1
if count==9:
print("---------")
#----------截断----------
f3=open("test_1",'a',encoding="utf-8")#'w'代表写文件
#f2.truncate(10) #从文件的第十个字符开始截断(一个空格算一个字符),后面的内容全部消失
#---指定截断(以下方法不可行)---
f3.seek(10) #将文件指针指向第十个字符
f3.truncate(20) #期望从第十个字符开始截断,这样会保留前三十个字符
#但实际 文件指针 对truncate()方法不起作用,该方法仍旧是从头开始计数
#----------读写----------
f4=open("test_1",'r+',encoding="utf-8") #'r+'代表读写文件
print(f4.readline().strip())
print(f4.readline().strip())
print(f4.readline().strip())
print(f4.tell())
f4.write("-----------------------")
print(f4.readline().strip()) #注:虽然期望将内容写入第四行,但运行后发现插入位置随机
#但其实事实就是这样的
#----------写读1----------
f5=open("test_1",'w+',encoding="utf-8") #'w+'代表写读文件
print(f5.readline().strip())
print(f5.readline().strip())
print(f5.readline().strip())
print(f5.tell())
f5.write("-----------------------")
print(f5.readline().strip()) #注:期望将内容写入第四行,但运行后发现原文件中内容被新写入的内容
#覆盖了
#----------写读2----------
f6=open("test_1",'w+',encoding="utf-8") # 期望先写入四行,然后将文件指针退回到第十个字符上,然后打印下一行的内容
#并在此时写入最后一行,但实际运行发现:我们所期望写入的位置并没有新的内容
#新内容被写在了最后一行
f6.write("-----------1------------\n")
f6.write("-----------2------------\n")
f6.write("-----------3------------\n")
f6.write("-----------4------------\n")
print(f6.tell())
f6.seek(10)
print(f6.readline())
f6.write("----------hello---------\n")
f6.close()
#----------二进制读文件----------
f7=open("test_1",'rb') #'rb'代表二进制读文件 注:此时后面encoding不能是"utf-8"
print(f7.readline())
#----------二进制写文件----------
f8=open("test_1",'wb') #'wb'代表二进制写文件 注:此时后面encoding不能是"utf-8"
f8.write("hello world\n".encode()) #注:encode ()中不指定具体的字符集,则以'utf-8'为默认
f8.close()
'''