Python——open()函数 文件处理

这篇博客介绍了Python中文件操作的基本模式,包括'r'(读)、'w'(写,覆盖原内容)、'a'(追加)等,并通过示例展示了如何使用这些模式进行文件读写。此外,还讲解了如何利用json模块进行数据存储和读取,以及如何复制文件,包括在同一目录及跨目录的文件复制方法。
摘要由CSDN通过智能技术生成

“”"模式参数
添加 ‘w’ 写入模式 告知Python 要写入文件 会覆盖原内容重新写入
‘r’ 读取模式
‘r+’ 读写模式
‘a’ 附加模式 不会覆盖原内容
调用 write() 函数写入
https://blog.csdn.net/u011811614/article/details/50832544
Character Meaning
‘r’ open
for reading (default)
‘w’ open
for writing, truncating the file first
‘a’ open
for writing, appending to the end of the file if it exists
‘b’ binary
mode
‘t’ text
mode (default)
‘+’ open
a disk file for updating (reading and writing)
‘U’ universal
newline mode (for backwards compatibility; should not be used in new code)
r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;
b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用、

常见的mode取值组合

r或rt 默认模式,文本模式读
rb 二进制文件

w或wt 文本模式写,打开前文件存储被清空
wb 二进制写,文件存储同样被清空

a 追加模式,只能写在文件末尾
a+ 可读写模式,写只能写在文件末尾

w+ 可读写,与a+的区别是要清空文件内容
r+ 可读写,与a+的区别是可以写到文件任何位置
“”"

# 'w'会覆盖原内容重新写入
with open(filename, 'w') as file_object:
    file_object.write("Wang Li qun\n")
    file_object.write("WWW\n")
    for i in range(5):
        file_object.write("I love Python\n")

# 'a'会覆盖原内容重新写入
with open(filename, 'a') as file_object:
    file_object.write("I also love C++\n")

“”"
json:
json.dump(存储内容,文件内容)
实参 = json.load(文件内容)
“”"
文件复制

‘’’
原文件: ‘C:\Users\Wanglq\Desktop\炉石\鲍勃.jpg’
目标文件: “C:\Users\Wanglq\Desktop\炉石\鲍勃1.jpg”

with open() 结合使用,可以自动释放资源 # with语句会让上下文管理器创建一个运行时上下文,当进入运行时上下文时自动调用特殊方法__enter__() 当离开运行时,上下文会自动调用特殊方法__exit__()。

‘’’

with open(r"C:\Users\Wanglq\Desktop\炉石\鲍勃.jpg", 'rb') as stream:
    container = stream.read()  # 读取文件内容

    with open(r"C:\Users\Wanglq\Desktop\炉石\鲍勃1.jpg", 'wb') as wstream:
        wstream.write(container)

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

跨文件夹复制

import os

print(os.path)
path = os.path.dirname(__file__)  # 获取当前文件 目录路径 (绝对路径)
print(path)
print(type(path))
path_file = os.path.join(path, '鲍勃.JPG')  # 在文件夹下拼接一个文件名
print(path_file)

with open(r'C:\Users\Wanglq\Desktop\炉石\鲍勃.jpg', 'rb') as stream:
    container = stream.read()

    with open(path_file, 'wb') as stream_w: # path_file 指定目录与复制后的文件名
        stream_w.write(container)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值