文件操作
f=open("test1.py",'rb',encoding="utf-8") #b的方式不能指定编码
f=open("test1.py",'rb') #b的方式不能指定编码
字符串 -》encode -》bytes
bytes -》decode -》字符串
b"hello" 可以转换ascii码
b=bytes(x,encoding="utf-8")
x.encode("utf-8")
文件的创建
context="""hello world""" f=open("hello.txt","w") f.write(context) f.close()
文件的读取
1、readline 方式读取
f=open("hello.txt") while True: line=f.readline() if line: print(line) else: break f.close()
2、readlines 方式读取
f=open("hello.txt")
lines=f.readlines()
for line in lines:
print(line)
f.close()
3、read 方式读取
f=open("hello.txt")
context=f.read()
print(context)
f.close()
f=open("hello.txt")
context=f.read(5)
print(context)
print(f.tell()) #返回文件对象当前指针位置
context=f.read(5)
print(context)
print(f.tell())
f.close()
文件的写入
f=open("hello.txt","w+") # w+ 用于读写一个文件,如果文件存在,则打开,原有内容被删除,进行写入 li=["hello world\n","hello China\n"] f.writelines(li) f.close()
f=open("hello.txt","a+") #追加方式
new_context="goodbye"
f.write(new_context)
f.close()
文件的删除
import os open("hello.txt","w") if os.path.exists("hello.txt"): os.remove("hello.txt")
文件的复制
src=file("hello.txt","w") li=["hello world\n","hello China\n"] src.writelines(li) src.close() #把hello.txt 复制到hello2.txt src=open("hello.txt","r") dst=open("hello2.txt","w") dst.write(src.read()) src.close() dst.close()
文件的重命名
import os li=os.listdir(".") print(li) if "hello2.txt" in li: os.rename("hello2.txt","hello3.txt") elif "hello3.txt" in li: os.rename("hello3.txt","hello2.txt")
files=os.listdir(".")
for filename in files:
li=os.path.splitext(filename) #对文件名进行解析,返回文件名和后缀名组成的列表
if li[1]==".html":
newname=li[0]+".htm"
os.rename(filename,newname)
文件内容的搜索和替换
import re f1=file("hello.txt","r") count=0 for s in f1.readlines(): li=re.findall("hello",s) if len(li)>0: count=count+li.count("hello") print("查找到"+str(count)+"个hello") f1.close()
f1=open("hello.txt","r")
f2=open("hello2.txt","w")
for s in f1.readlines():
f2.write(s.replace("hello","hi"))
f1.close()
f2.close()
文件的比较
import difflib f1=open("h1.txt","r") f2=open("h2.txt","r") src=f1.read() dst=f2.read() print(src) print(dst) s=difflib.SequenceMatcher(lambda x:x=="",src,dst) # lambda x:x==""表示忽略h2中的换行符。如果h2.txt中有多余的换行,并不会作为不同点返回
for tag,i1,i2,j1,j2 in s.get_opcodes(): print("%s src[%d:%d]=%s dst[%d:%d]=%s" %\ (tag,i1,i2,src[i1:i2],j1,j2,dst[j1:j2]))
配置文件的访问
#读配置文件 import configparser config=configparser.ConfigParser() config.read("ODBC.ini") sections=config.sections() print("配置块:",sections) o = config.options("ODBC 32 bit Data Sources") print("配置项:",o) v = config.items("ODBC 32 bit Data Sources") print("内容:",v) access=config.get("ODBC 32 bit Data Sources","MS Access Database") print(access) excel=config.get("ODBC 32 bit Data Sources","Excel Files") print(excel) dBASE= config.get("ODBC 32 bit Data Sources","dBASE Files") print(dBASE) #写配置文件import configparser config=configparser.ConfigParser() config.add_section("ODBC Driver Count") config.set("ODBC Driver Count","count",2) f=open("ODBC.ini","a+") config.write(f) f.close() #修改配置文件 import configparser config = configparser.ConfigParser() config.read("ODBC.ini") config.set("ODBC Driver Count","Count",3) f = open("ODBC.ini","r+") config.write(f) f.close() #删除配置文件 import configparser config =configparser.ConfigParser() config.read("ODBC.ini") config.remove_option("ODBC Driver Count","count") config.remove_section("ODBC Driver Count") f = open("ODBC.ini","w+") config.write(f) f.close()
目录的常见操作
#创建和删除目录 import os os.mkdir("hello") os.rmdir("hello") os.makedirs("hello/world") #创建多级目录 os.removedirs("hello/world") #删除多级目录 #目录的遍历 # 递归遍历目录 import os def VisitDir(path): li=os.listdir(path) for p in li: pathname = os.path.join(path,p) if not os.path.isfile(patname): VisitDir(pathname) else: print(pathname) if __name__ == "__main__": path = r"D:\developer\python\example\07" VisitDir(path) # os.walk() import os def VisitDir(path): for root,dirs,files in os.walk(path): for filepath in files: print(os.path.join(root,filepath)) if __name__ == "__main__": path = r"D:\developer\python\example\07" VisitDir(path)
文件和流
浙公网安备 33010602011771号