python 文件读取和写入

写数据到文件

def upload_file(request):
    try:
        if request.method == "POST":
            data = request.FILES['data']
            assert data, '参数必传 data'
            num = random.randint(0, 100)
            file_name = os.path.join(settings.BASE_DIR, 'media/resume{}'.format(num))
            try:
                obj = open(file_name, 'wb+')
                for chunk in obj.chunks():  # 将文件写入磁盘
                    obj.write(chunk)
                obj.close()
                # with open(file_name, 'wb+') as f:
                #     f.write(data)
                return HttpResponse(num)
            except Exception as e:
                logger.error(e)
                return JsonResponse({
                    "status": "failed",
                    "code": 400,
                    "msg": str(e)
                })
    except AssertionError as e:
        logger.error(e)
        return JsonResponse({
            "status": "failed",
            "code": 400,
            "msg": str(e)
        })
    except Exception as e:
        logger.error(e)
        return JsonResponse({
            "status": "failed",
            "code": 400,
            "msg": str(e)
        })
# 1.03 读取图片demo
def read_img(request):
    """
    : 读取图片
    :param request:
    :return:
    """
    try:
        data = request.GET
        file_name = data.get("file_name")
        imagepath = os.path.join(settings.BASE_DIR, "static/resume/images/{}".format(file_name))
        with open(imagepath, 'rb') as f:
            image_data = f.read()
        return HttpResponse(image_data, content_type="image/png")
    except Exception as e:
        print(e)
        return HttpResponse(str(e))
# 读取整个文件
with open('pi_digits.txt') as f: # 默认模式为‘r’,只读模式
    contents = f.read() # 读取文件全部内容

# 逐行读取
with open('pi_digits.txt') as f:
    for line1 in f:
        print line1 # 每行末尾会有一个换行符
    print '------------'
    for line2 in f:
        print line2.rstrip() # 此时文件已经读完,line2指向文本末尾,因此不会有输出



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值