Python语法之文件操作思维导图

it2025-06-24  9

 

文件IO代码

import io import sys import os import shutil sys.stdout = io.TextIOWrapper(sys.stdout.detach(),encoding='utf-8') # 打开一个指定文件,指定编码格式:utf-8 file = open('E:\\resource.txt','r',encoding='utf-8') print(file) # 关闭指定文件 file.close() # 使用with 打开指定文件,并指定编码格式 with open('E:\\resource.txt','r',encoding='utf-8') as file: print(file) # 文件内容写入 # 打开一个指定文件,指定编码格式:utf-8 file = open('E:\\resource.txt','w',encoding='utf-8') file.write('Python3 write函数 功能实现') # 关闭指定文件 file.close() # 文件内容读取 # 打开一个指定文件,指定编码格式:utf-8 file = open('E:\\resource.txt','r',encoding='utf-8') string = file.read(8) print(string) # 关闭指定文件 file.close() # 文件内容读取,从指定位置开始读取 # 打开一个指定文件,指定编码格式:utf-8 file = open('E:\\resource.txt','r',encoding='utf-8') file.seek(5) string = file.read(8) print(string) # 关闭指定文件 file.close() # 文件内容读取,按行读取并输出 # 打开一个指定文件,指定编码格式:utf-8 with open('E:\\resource.txt','r',encoding='utf-8') as file: line = file.readline() print(line) # 文件内容读取,读取全部内容并输出 # 打开一个指定文件,指定编码格式:utf-8 with open('E:\\resource.txt','r',encoding='utf-8') as file: line = file.readlines() print(line) # os 或者os.path 读取系统有关信息 print(os.name) #获取操作系统类型 print(os.linesep) # 获取操作系统的换行符 print(os.sep) # 获取操作系统所使用的路径分隔符 # 获取当前工作目录(相对路径) print(os.getcwd()) # 绝对路径 print(os.path.abspath("1.txt")) #路径拼接 print(os.path.join("d:\\python_workspace\\two","1.txt")) # 指定目录是否存在 print(os.path.exists("d:\\python_workspace")) # 创建一级目录 #os.mkdir("D:\\one") # 优化创建一级目录 path = "D:\\two" if not os.path.exists(path): os.mkdir(path) print("目录创建成功") else: print("目录已经存在") # 创建多级目录 # os.makedirs("D:\\two\\three\\one") # print("多级目录创建成功") # 目录删除 # path = "D:\\two\\three\\one" # if os.path.exists(path): # os.rmdir(path) # print("目录删除成功") # else: # print("目录不存在") # 目录删除 # path = "D:\\two\\three\\one" # if os.path.exists(path): # shutil.rmtree(path) # print("目录删除成功") # else: # print("目录不存在") # 目录遍历 tuples = os.walk("D:\\two\\three\\one") for item in tuples: print(item,'\n') # 文件删除 path ="1.txt" if os.path.exists(path): os.remove(path) print("文件删除成功") else: print("指定文件不存在") # 文件重命名 path ="1.txt" if os.path.exists(path): os.rename(path,"2.txt") print("文件重命名成功") else: print("指定文件不存在") # 文件信息读取 path = "2.txt" if os.path.exists(path): fileInfo = os.stat(path) print("文件大小:",fileInfo.st_size) print("文件最后一次修改时间",fileInfo.st_mtime)

 

最新回复(0)