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

虾米姐 阅读:677 2021-03-31 13:41:58 评论:0

 

文件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)

 

标签:Python
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号