1、文件操作
文件操作分为3步:
1)、打开文件,得到一个文件句柄,并赋给一个变量;
2)、通过句柄,对文件进行操作;
3)、关闭文件;
#打开文件
f = open("a.txt",encoding='utf-8')
print(f.read())
f.close()
#写文件,覆盖原来文件;
f = open('a.txt','w',encoding='utf-8')
#写文件,在原文件后追加
f= open('a.txt','a',encoding='utf-8')
#!/usr/bin/env python
# -*- coding:utf-8 -*-
f= open("a.txt",encoding="utf-8")
# for index,line in enumerate(f.readlines()):
# if index==9:
# print ("-----分割线------")
# else:
# print(line.strip())
#如果遇到一个大文件,20G
count =0
for line in f:
if count==3:
print ("----分割线----")
else:
print(line.strip())
count+=1
print (f.tell()) #文件句柄指针位置;
print (f.encoding) #打印文件编码;
f.flush() #刷新
#----------------------------------
f = open("a.txt",'a',encoding="utf-8")
f.truncate(20)
#以追加方式打开,只留20个字符;
#flush 作用,类似进度条功能;
import sys,time
for i in range(10):
sys.stdout.write("#")
sys.stdout.flush() #如不加此句,则统一缓存后再输出;
time.sleep(0.1)
#文件读写:
f=open("a.txt","r+") #打开在末尾写入;
print (f.read())
print (f.read())
print(f.read())
f.write("----xie---------")
#上述读写模式,不会象上例一样,在第三行写入内容,实际写入内容会在原文件最后写入;
#文件写读;
f=open("a.txt","w+")#清空并读写;
#文件写读,先清空文件,写入、读取、再写入内容追入到最后;
#追加读;
f = open("a.txt","a+")
f.write("hello world;")
f.seek(0)
print (f.read())
#二进制读写
f= open("a.txt","rb")
#网络传输
#二进制读写;
f = open("a.txt","wb")
f.write("hello world\n".encode())
#文件修改:
f = open("yes",encoding="utf-8")
f_new= open("yes_new_bak",'w',encoding="utf-8")
for line in f:
if "肆意的快乐" in line:
line = line.replace("肆意的快乐","哈哈")
f_new.write(line)
f.close()
f_new.close()