通知短信+运营短信,5秒速达,支持群发助手一键发送🚀高效触达和通知客户 广告
[TOC] ## open() 打开文件 ## read() | code | 说明 | | --- | --- | | read([size]) | 读取文件(读取size个字节,默认读取全部) | | readline([size])) | 读取一行(设置了size, 一行中读取size字节) | | readlines([size]) | 读取完文件,返回每一行组成的列表) | | iter() | 迭代器 | *iter()* f = open('README.md',encoding='utf-8'); content = iter(f) for line in content: print(line) ## write >写函数只有在f.close()关闭后在会写入文件 >如想在f.close()前写入 使用f.flush() write(str) writelines(sequence_of_strings) : #写多行到文件 ## 文件指针 >seek(offset[,whence]) :移动文件指针 >offset :偏移量,可以为负数 >whence :偏移相对位置 ```python #whence的值如下 os.SEEK_SET # 相对文件起始文职 os.SEEK_CUR # 相对文件当前位置 os.SEEK_END # 相对文件结尾位置 f.fileno() #文件描述符 f.mode #文件打开权限 f.encoding #文件编码格式 f.closed #文件时否关闭 ``` demo ```python f = open("1.txt",'r+') f.tell() #0 #f.tell() 当前文件位置 f.read(3) f.tell() #3 f.seek(0,os.SEEK_SET) # 相对文件结尾偏移0 f.tell() #0 ``` ## 操作ini 文件 ```python #创建 demo.ini [userinfo] name = zhangsan pwd = abc [study] python_base = 15 python_junior = 20 linux_base_ = 15 #打印 参数 import configparser cfg = configparser.ConfigParser() f = cfg.read('demo.ini') print(f[0]) #demo.ini cfg.set("userinfo",'wpd','12345612') #修改/添加 cfg.remove_section('userinfo') #删除 section cfg.remove_option('userinfo','pwd') #删除 option for se in cfg.sections(): print(se) #userinfo print(cfg.items(se)) #[('name', 'zhangsan'), ('pwd', 'abc')] fp = open(f[0],'w') cfg.write(fp) #保存 fp.close() ```