python 文件操作

python 文件读写

文件操作模式

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,先写再读。【这个方法打开文件会清空原本文件中的所有内容,将新的内容写进去,之后也可读取已经写入的内容】
  • a+,同a

写入

覆盖写入

ss='世情薄,人情恶,雨送黄昏花易落。'
with open('1.txt', 'w', encoding='utf-8') as f:
    f.write(ss)
f.close()
View Code

读取

1.

try:
    f=open('1.txt','r',encoding='utf-8')
    print(f.read())
finally:
    if f:
        f.close()
View Code

2.逐行读取

try:
    f=open('1.txt','r',encoding='utf-8')
    print(f.readlines())#一次读取每一行组成列表
    print(f.readline())#每次读取一行
finally:
    if f:
        f.close()
View Code

 多媒体文件操作

f1=open('my.png','rb')
with open('my1.png', "wb") as f:
    for line in f1:
        f.write(line)
View Code

上传

file_obj = request.FILES.get("kouge")
with open(file_obj.name, "wb") as f:
    for line in file_obj.chunks():
        f.write(line)
View Code
原文地址:https://www.cnblogs.com/huay/p/10837720.html