码迷,mamicode.com
首页 > 其他好文 > 详细

文件操作

时间:2018-08-17 11:22:25      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:content   视频   src   lin   sed   路径   nbsp   存储   exti   

# 打开文件
# open(‘文件路径‘,‘打开方式‘,‘指定编码方式‘)
# 文件路径 绝对路径 相对路径
# 打开方式 r w a + b
# 编码方式 utf-8 gbk ..
# 以什么编码存储的文件 就以什么编码打开进行操作
# 视频 图片等以二进制方式读(按字节读)


# 关闭文件
#f.close()

# 操作文件
# r只读 
# rb以二进制方式读
技术分享图片
# r只读   str类型
# f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)
# print(type(f))#_io.TextIOWrapper
# content=f.read()
# print(content,type(content))
# f.close()

#r只读
# with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘) as f:
#     content=f.read()
#     print(content)

# rb以二进制方式读  bytes类型
# 读出的换行符\r\n
# with open(‘a.txt‘,‘rb‘) as f:
#     content=f.read()
#     print(content)
View Code
# w 写
# 没有文件即创建 内容覆盖
#wb 以二进制方式写入
技术分享图片
# w 写
# 没有文件即创建 内容覆盖
# with open(‘a.txt‘,‘w‘,encoding=‘utf-8‘) as f:
#     f.write(‘welcome‘)

#wb 以二进制方式写入
# with open(‘a.txt‘,‘wb‘)as f:
#     f.write(‘welcome‘.encode(‘utf-8‘))
View Code
# a追加 
# ab以二进制方式追加
技术分享图片
# a追加
# with open(‘a.txt‘,‘a‘,encoding=‘utf-8‘)as f:
#     f.write(‘beijing‘)

# ab以二进制方式追加
# with open(‘a.txt‘,‘ab‘)as f:
#     f.write(‘beijing‘.encode(‘utf-8‘))
View Code
# r+读写
# r+b以二进制方式读写
技术分享图片
# r+读写
# with open(‘a.txt‘,‘r+‘,encoding=‘utf-8‘) as f:
#     content=f.read()
#     f.write(‘welcome‘)
#     print(content)

#r+b以二进制方式读写
# with open(‘a.txt‘,‘r+b‘) as f:
#     content=f.read()
#     f.write(‘welcome‘.encode(‘utf-8‘))
#     print(content)
View Code
#seek按照字节定义光标的位置
#tell光标所在位置(按字节)
#readable是否可读
技术分享图片
#seek按照字节定义光标的位置
#tell光标所在位置(按字节)
#readable是否可读
# with open(‘a.txt‘,‘r+‘,encoding=‘utf-8‘)as f:
#     f.write(‘世界‘)
#     f.seek(0)
#     print(f.tell())
#     print(f.readable())
View Code
#read读出指定个数的字符 (包括换行符)
#readline 一行一行读
#readlines 返回列表 每行成列表中的元素 包括换行符\n
技术分享图片
#seek按照字节定义光标的位置
#tell光标所在位置(按字节)
#readable是否可读
# with open(‘a.txt‘,‘r+‘,encoding=‘utf-8‘)as f:
#     f.write(‘世界‘)
#     f.seek(0)
#     print(f.tell())
#     print(f.readable())

#read读出指定个数的字符 (包括换行符)
#readline 一行一行读
#readlines 返回列表 每行成列表中的元素 包括换行符\n
# f=open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)
# print(f.read(5))
# print(f.readline())
# print(f.readlines())

# 推荐读法
# for i in f:
#     print(i)
# f.close()
View Code
#同时操作文件
技术分享图片
#同时操作文件
# with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)as f1,open(‘b.txt‘,‘w‘,encoding=‘utf-8‘)as f2:
#     content=f1.read()
#     print(content)
#     f2.write(content)
View Code
#修改文件的本质
技术分享图片
#修改文件的本质
# with open(‘a.txt‘,‘r‘,encoding=‘utf-8‘)as f1,open(‘a.bak‘,‘w‘,encoding=‘utf-8‘)as f2:
#     for line in f1:
#         if ‘alex‘ in line:
#             line=line.replace(‘alex‘,‘‘)
#         f2.write(line)#写文件
#
# import os
# os.remove(‘a.txt‘)#删除文件
# os.rename(‘a.bak‘,‘a.txt‘)#重命名
View Code

 






文件操作

标签:content   视频   src   lin   sed   路径   nbsp   存储   exti   

原文地址:https://www.cnblogs.com/liuhongshuai/p/9491807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!