继续整理python------文件操作

100 阅读1分钟

简单的话,系统函数open()把文件进行流操作。

文件操作

# 文件操作  
'''  
常用的mode:  
r 只读 ,文件/路径不存在时会报错,有返回值  
rb 使用二进制读取,适用于图片、视频等  
w 写 ,写文件内容  
wb 使用二进制写,适用于图片、视频等
a 追加,不会清空原来的内容  
'''  

# 读取文本  
stream = open(file='a.txt',mode='r',encoding='utf-8')  
# 与readline类似,读取的内容保存到列表  
print(stream.readlines())  
# readline要注意读取位置,读取一行内容,循环读取会自动换行  
print(stream.readline())  
# 读取文本内容,读取所有内容  
print(stream.read())  
# 判断文件是否可读  
print(stream.readable())  
  
# 读取图片,mode要传rb  
pic = open(file='style.jpg',mode='rb')  
print(pic.read())  
  
w = open(file='a.txt',mode='w',encoding='utf-8')  
content = '''  
您好,太初!  
asd  
asddss  
'''  
# 写入内容,会把文本内容清空后再写入,返回内容长度  
print(w.write(content))  
# 判断文件是否可写  
print(w.writable())  
# 文本末尾追加内容,可写入列表但没有换行效果  
print(w.writelines(['我是追加的内容!\n','asd\n','dddddd\n']))  
  
# 释放管道,避免占用内产  
w.close()  
  
# 模式是a,不回清除内容,直接追加  
a = open(file='a.txt',mode='a',encoding='utf-8')  
content = 'xxxxxxxxxxxx'  
print(a.write(content))

with

文件的复制原理:先读取后写。

# 文件的复制  
'''  
源文件:  
目标文件:  
原理:先读取后写  
'''  
# r = open(file='style.jpg',mode='rb')  
  
# with可以帮助我们自动时候资源  
with open(file='style.jpg',mode='rb') as r:  
    container = r.read()  
with open(file=r'D:\pyScript\learn\style.jpg',mode='wb') as w:  
    w.write(container)

os模块

import os  
  
## __file__当前文件  
# 获取当前文件目录--绝对路径,返回字符串  
path = os.path.dirname(__file__)  
print(path)  
  
# 路径拼接join  
new = os.path.join(path,'b.txt')  
print(new)