python(17)文件操作

一、文件操作模式及操作流程

1、mode(模式): 

r : read  w : write  纯文本文件

b : binary 二进制 字节

rb : read binary   wb : write binary  纯文本、图片、音乐、电影

read  in 输入

write out 输出

 

2、文件操作流程

客户:

文件上传——读硬盘并上传到网盘——写入网盘

文件下载——读网盘的文件——写入自己的硬盘

 

网盘:

缓存:调节硬件与CPU的缓冲

网盘——缓存——获取网盘文件

上传文件为流——写入缓存——写入网盘

 

二、文件上传

系统函数:open(file, mode, buffering, encoding)

读:  open(path/filename, 'rt')  mode:rt 读文本文档   --->返回值:stream(管道)

stream.read()  --->读取管道中内容

注意:如果传递的path/filename 有误,则会报错,FileNotFoundError

     如果是图片,则不能使用默认的读取方式, mode = 'rb'

 

总结:

read()          读取所有内容

readline()      每次读取一行内容

readlines()     读取所有行保存到列表中

readable()      判断是否可读

读取text文件:

#打开aa.txt文件
stream = open(r'D:\JY\test\aa.txt')
# read()  读流中所有信息
container = stream.read()
print(container)

result = stream.readable()  #判断文件是否可以读取
print(result)

lines = stream.readlines()  #保存到列表中
print(lines)    #输出:['测试内容\n', 'hello world']
等价于:
while True:
    line = stream.readline()    #读取一行内容
    print(line)
    if not line:
        break
#读图片
stream = open(r'D:\JY\test\Tulips.jpg', 'rb')
container = stream.read()
print(container)

 

三、文件下载

stream = open(r'D:\JY\aa.txt', 'w')

mode 是 'w' 表示就是写操作

方法: 

write(内容)    每次都会将原来的内容清空,然后写当前的内容

writelines(Iterable)  没有换行效果,需要自行加\n

 

如果mode = 'a'  追加        append

stream = open(r'D:\JY\test\aa.txt', 'a')

#写文件
stream = open(r'D:\JY\aa.txt', 'a')
s = '''
你好!
    欢迎来到游戏中,赠送给你一个金币!
                落款:name
'''
result = stream.write(s)
print(result)
# stream.close()  #释放资源(写完后关闭管道)

stream.writelines("hello world")
stream.writelines(['test1\n', 'information\n', 'test2\n'])
stream.close()

 

四、文件复制并粘贴

原文件      D:\JY\test\Tulips.jpg

目标文件:  D:\JY\test1\Tulips.jpg

原——in read mode='rb' —— out write mode='wb'

 

with open() as ...

with结合open使用,可以帮助我们自动释放资源

os.path

os.path.dirname(__file__)  获取当前文件所在的文件目录(绝对路径)

 

例:将指定路径中图片,读取并写入本文件目录中

# 模块; xxx.py
# os.py  操作系统内置模块
import os
print(os.path.dirname(__file__))  # 当前文件所在的文件目录(绝对路径)

with open(r'D:\JY\test\Tulips.jpg', 'rb') as stream:
    container = stream.read()  # 读取文件内容
    print(stream.name)  # 文件路径及名称
    file1 = stream.name
    filename = file1[file1.rfind('\\') + 1 :] # 截取文件名
    
    # with open(r'D:\JY\test1\Tulips.jpg', 'wb') as wsteam:
    # 在本文件目录中,join连接文件名,并将通道流中写入
    path = os.path.dirname(__file__)
    path1 = os.path.join(path, filename)
    with open(path1, 'wb') as wsteam:
        wsteam.write(container)     # 缓存内容写入

print('文件复制完成!')

 

with  open()  as  ...    会自动将流close

如果指定的文件不存在,则自动创建

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章