文件处理、进度条
1、流程
- 打开文件
open()
with open("file") as 文件句柄:
## mode="" r=可读模式,w=可写模式(覆盖清空),a=追加模式,X=写(如果文件存在则报错,不会覆盖) f = open("test2.py",mode="a",encoding="utf-8")## 可读可写模式 r+ w+ a+ ## r+=可读写(0位置读,光标位置写)、w+=可读写(光标位置读,覆盖清空写)、a+=可读写(NF位置读,追加写) ## seek(0) 将光标移动到指定位置(按字节位置)(可用于断点续传功能) ## tell() 打印光标所在位置(按字节位置)rb、wb、ab、二进制操作 - 操作文件
read、write
print(f.read()) ## 读入全部内容 print(f.read(5)) ## 5代表只读5个字符,如果不加则全部读入。(py2里是按字节读入) print(f.readline()) ## 按行读入 print(f.readlines()) ## 列表读入剩下所有行 print(f.readable()) ## 判断是否为可读入文件,布尔值表示f.write("hello test2\n") ## w覆盖写入,之前内容会清空。a为追加 f.flush() ## 将内存里的缓存立刻刷新到磁盘上保存writelines([字符串,字符串]) # 可添加多个字符串写入
with open("test.py","w") as f: # f.write(["111111\n","11111\n"]) ## 使用 write 则不能同时添加多个字符串写入 f.writelines(["1111\n","111111\n"])truncate(字节) # 按字节截断。剩余的内容清除
with open("test.py",mode="r+") as f: f.writelines(["123456\n","111111\n","222222"]) f.seek(0) f.truncate(3) print(f.read()) ------------------------------------------------------------ 123文件更名: os.rename("name","new name") # 需要提前调用 os
import os ## 调用 os 函数 os.rename("test.py","test.back") os.rename("test2.py","test.py") - 关闭文件
close()
------------------------------------------------------------------------------------------------------
with open("file") as 文件句柄: ## 等同于 文件句柄=open("file")
缩进内的操作 ………………
………………
## 使用with的好处就是,如果打开文件操作后忘记使用 close进行文件关闭操作,with下缩进的操作执行完毕后,跳出with会自动加上 close 关闭文件的操作 - 进度条
import sys for n in range(100): s = "\r%d%% %s"%(n,"#"*n) sys.stdout.write(s) sys.stdout.flush() import time time.sleep(0.5)

浙公网安备 33010602011771号