python 文件读取和写入

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/baidu_39416074/article/details/80930549

写数据到文件

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指向文本末尾,因此不会有输出



猜你喜欢

转载自blog.csdn.net/baidu_39416074/article/details/80930549
今日推荐