“”"模式参数
添加 ‘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)