open
#复制文件
readfile = open("174.txt","r")
info = readfile.read()
readfile.close()
writefile = open("174-3.txt","w")
writefile.write(info)
writefile.close()
---------------------------------------------------
readfile = open("壁纸.jpg","rb")
info = readfile.read()
readfile.close()
writefile = open("壁纸-2.jpg","wb")
writefile.write(info)
writefile.close()
--------------------------------------
file2 = open("174-4.txt","w+")
file2.write("test info")
info = file2.read()
file2.close()
with open
with open ("111.txt","w")as file: # w表示写文本文件(存在则覆盖),wb表示写二进制文件
file.write("aaaabbbbccccdddd")
with open("111.txt","a")as file: # 以追加的方式写入
file.write("11111111")
--------------------------------
#先读取文件再写入文件
with open("111.txt","r")as file: # r表示读操作
info = file.read()
print("读到的信息是:"+info)
with open("888.txt","w")as file:
file.write(info)
---------------------------------
with open("174.txt","r") as file :
# file.write("hello python itcast2") # 不允许进行写操作
info = file.read()
print("读取到的信息是:"+info)
两种方式的区别
最大的区别就是with open
在操作结束之后会自动调用close函数帮助我们关闭文件,防止内存泄漏; 而 open
则需要我们手动关闭
并且open在读取文件的时候,如果文件不存在,会报错FileNotFoundError
With open打开文件的参数
r
以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
w
打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a
打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
rb
以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
wb
以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
ab
以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
r+
打开一个文件用于读写。文件指针将会放在文件的开头。
w+
打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a+
打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
rb+
以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
wb+
以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
ab+
以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
flask从前端读取图片保存
image = request.files['image'].read()
number= request.form.get('number')
photo_dir = '/program/photos/' + number
if not os.path.exists(photo_dir):
os.mkdir(photo_dir)
photo_name = number+ '-' + str(round(time.time()*1000)) + '.jpg' # 时间戳精确到毫秒
image_path = os.path.join(photo_dir, photo_name) #保存路径
try:
with open(image_path, 'wb') as tmp:
tmp.write(image) # 写入文件
except Exception as e:
print(e)
return error.SavePhotoFailed
# 指定路径的html模板
html_path = os.path.abspath(os.path.dirname(__file__))
html_tmp = os.path.join(html_path, 'emailtmp{}.html'.format(self.mode))
f = open(html_tmp, 'r', encoding='utf-8')
mail_body = f.read()
f.close()