10.文件操作
import os # __file__ print("文件绝对路径(含文件名)",__file__) # os.getcwd() print("获取绝对路径(不含文件名)",os.getcwd()) # os.path.abspath(path) print("获取相对路径的绝对路径",os.path.abspath(".")) # os.path.isabs(path) print("判断参数是否为绝对路径",os.path.isabs(os.getcwd())) # os.path.relpath(path,start) print("返回从start路径到path路径的相对路径",os.path.relpath("C:\\ORA",".")) # os.path.dirname(path),os.path.basename(path),os.path.split(path) path1 = __file__ print("获取文件路径",path1) print("返回路径",os.path.dirname(path1)) print("返回文件名",os.path.basename(path1)) print("同时返回路径和文件名到一个元组中",os.path.split(path1)) # os.path.exists(path),os.path.isdir(path),os.path.isfile(path) print("判断路径或文件是否存在",os.path.exists(path1)) print("判断path是否为路径",os.path.isdir(path1)) print("判断path是否为文件",os.path.isfile(path1)) # os.remove(),删除文件 # os.remove("a.txt") # file = open(file_name [, mode='r' [ , buffering=-1 [ , encoding = None ]]]) # mode:默认"r"只读 # buffering:是否使用缓冲区,默认-1代表使用默认的缓冲区大小 # encoding:编码格式,默认cp936(即GBK编码) f1 = open('module_test.py') # 以默认方式打开文件 print("输出文件是否已经关闭",f1.closed) print("输出访问模式",f1.mode) print("输出编码格式",f1.encoding) print("输出文件名",f1.name) f1.close() # file.read([size]),逐字节或字符读取文件(size省略,则一次性读取所有内容) f2 = open("module test.py",encoding = "utf-8") print("读取10个字符",f2.read(10)) print("读取整个文件",f2.read()) f2.close() # file.readline([size]),逐行读取文件(size用于读取每一行时,一次最大读取的字符或字节数) f3 = open("module test.py",encoding = "utf-8") print("读取一行",f3.readline()) f3.close() # file.readlines(),一次性读取多行,与read()类似,只不过返回一个字符串列表,每个元素为文件中的一行内容 f4 = open("module test.py",encoding = "utf-8") for i in f4.readlines(): print("for循环输出readlines()",i) f4.close() # file.write(string) f5 = open("test.txt","w") f5.write("写入一行数据") f5.flush() # 文件写入数据后,不想马上关闭文件,可以调用flush()函数,将缓冲区的数据写入文件中 f5.close() # file.writelines([str]) # [str]:字符串序列 r = open("module test.py") w = open("test.txt","w") w.writelines(r.readlines()) # writelines()写入数据时,不会自动换行。这个地方换行是因为readlines()读的数据带换行符 r.close() w.close() # file.tell()和file.seek(offset[,whence]) # whence:指定文件指针位置,0:文件头(默认),1:当前位置,2:文件尾 # offset:相对于whence的偏移量,正数向后偏移,负数向前偏移(offset为负数时,文件必须以二进制格式打开) f6 = open("module test.py") f6.seek(3) print("seek后的位置",f6.tell()) # 读取文件指针当前位置 print("从seek后的位置读整行:",f6.readline()) # with as,确保语句执行完毕后,自动关闭已经打开的文件(哪怕文件操作期间出现异常也会关掉) '''格式: with 表达式 [as target]: # target用于接收表达式的返回 代码块''' with open("test.txt","w") as f: f.write("with as打开文件输入值") # 序列化pickle库,实现python对象的持久化存储 # dumps():将python中的对象序列化成二进制对象,并返回 # loads():读取给定的二进制对象数据,并转换成python对象 # dump():将python中的对象序列化成二进制对象,并写入文件 # load():读取指定的序列化数据文件,并返回对象(局限性:不适合读取海量数据) import pickle in1 = ['111','2222','3333'] out1 = pickle.dumps(in1) print('python对象转换成二进制对象',out1) in1 = pickle.loads(out1) print('二进制对象转换成python对象',in1) with open('test_pickle.txt','wb') as f: pickle.dump(in1,f) # 将对象转换成二进制对象,写入文件 with open('test_pickle.txt','rb') as f: out1 = pickle.load(f) # 读取序列化文件(局限性:不适合读取海量数据) print(out1) # fileinput模块,逐行读取多个文件 # 格式:fileinput.input(files="file1, filen2, ...", inplace=False, backup='', bufsize=0, mode='r', openhook=None) # files:多个文件的路径列表; # inplace:用于指定是否将标准输出的结果写回到文件,此参数默认值为 False; # backup:用于指定备份文件的扩展名; # bufsize:指定缓冲区的大小,默认为 0; # mode:打开文件的格式,默认为 r(只读格式); # openhook:控制文件的打开方式,例如编码格式等 import fileinput files = ['module_test.py','test.txt'] for line in fileinput.input(files): # 读取文件内容的次序,按照文件名的先后次序,读完一个再读另一个 print('fileinput读取文件',line) fileinput.close() # linecahce模块,读取指定文件中指定行(只能以utf-8读取文件) import linecache print('linecache读取指定行(读第一行)',linecache.getline('10.文件操作.py',1)) # pathlib模块 # UNIX 系统路径使用的分隔符是斜杠(/),而 Windows 使用的是反斜杠(\) from pathlib import * path1 = PurePath('d','test.txt') path2 = PurePosixPath('d','test.txt') print('PurePath',path1) print('PurePosixPath',path2) # os.path模块 from os import path print('获取绝对路径',path.abspath('test.txt')) print('获取共同前缀',path.commonprefix(['C://my_file.txt', 'C://a.txt'])) print('获取共同路径',path.commonpath(['http://c.biancheng.net/python/', 'http://c.biancheng.net/shell/'])) print('获取目录',path.dirname('C://my_file.txt')) print('判断指定目录是否存在',path.exists('my_file.txt')) # fnmatch模块 # fnmatch.filter(names, pattern):对 names 列表进行过滤,返回 names 列表中匹配 pattern 的文件名组成的子集合。 # fnmatch.fnmatch(filename, pattern):判断 filename 文件名,是否和指定 pattern 字符串匹配 # fnmatch.fnmatchcase(filename, pattern):和 fnmatch() 函数功能大致相同,只是该函数区分大小写。 # fnmatch.translate(pattern):将一个 UNIX shell 风格的 pattern 字符串,转换为正则表达式 import fnmatch #filter() print(fnmatch.filter(['dlsf', 'ewro.txt', 'te.py', 'youe.py'], '*.txt')) #fnmatch() for file in ['word.doc','index.py','my_file.txt']: if fnmatch.fnmatch(file,'*.txt'): print(file) #fnmatchcase() for file in ['word.doc','index.py','my_file.txt','a.TXT']: if fnmatch.fnmatchcase(file, '*.txt'): print(file) #translate() print(fnmatch.translate('a*b.txt')) # tempfile模块,生成临时文件和临时目录 # 方式一、手动创建临时文件,读写临时文件后需要主动关闭它,当程序关闭该临时文件时,该文件会被自动删除。 # 方式二、使用 with 语句创建临时文件,这样 with 语句会自动关闭临时文件。 import tempfile # 创建临时文件 fp = tempfile.TemporaryFile() print(fp.name) fp.write('两情若是久长时,'.encode('utf-8')) fp.write('又岂在朝朝暮暮。'.encode('utf-8')) # 将文件指针移到开始处,准备读取文件 fp.seek(0) print(fp.read().decode('utf-8')) # 输出刚才写入的内容 # 关闭文件,该文件将会被自动删除 fp.close() # 通过with语句创建临时文件,with会自动关闭临时文件 with tempfile.TemporaryFile() as fp: # 写入内容 fp.write(b'I Love Python!') # 将文件指针移到开始处,准备读取文件 fp.seek(0) # 读取文件内容 print(fp.read()) # 通过with语句创建临时目录 with tempfile.TemporaryDirectory() as tmpdirname: print('创建临时目录', tmpdirname)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步