python 파일 읽기 및 쓰기

2497 단어

파일로 데이터 쓰기

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 , 

좋은 웹페이지 즐겨찾기