Skip to main content
  1. Note/

Python: Read File(BinaryIO) Multiple Time

·1 min· ·
Blog En Python
Liu Zhe You
Author
Liu Zhe You
Skilled in full-stack development and DevOps, currently focusing on Backend.
Table of Contents

Python: read file(BinaryIO) multiple time
#

Recently, I need to read BinaryIO object multiple time when handling Minio file.

solution : seek(0)
#

The reason is that the cursor of BinaryIO object will stay at the end of the file after reading it. So, we need to reset the cursor by seek(0).

f = open(f)
content = f.read()

f.seek(0) # reset !!!!
content = f.read()

Read UploadFile object multiple time in FastAPI
#

Because UploadFile object in FastAPI also encapsulates BinaryIO object. We can also reset the cursor by seek(0).

from fastapi import FastAPI, UploadFile, status

def file_service(upload_file: UploadFile):
  content = upload_file.file.read() # first read
  another_file_service(upload_file)
  return status.HTTP_200_OK

def another_file_service(upload_file: UploadFile):
  upload_file.file.seek(0) # need to reset cursor !!!!
  content = upload_file.file.read() # third read

reference
#

https://stackoverflow.com/questions/3906137/why-cant-i-call-read-twice-on-an-open-file

Related

PgBouncer: Lightweight Postgres Connection Pool
·2 mins
Blog Database En Postgresql
Solving Django backend DB connection overload with PgBouncer
Cloudflare Tunnel
·3 mins
Blog En
Setup Cloudflare Tunnel for NAT, an alternative to Ngrok
Tmux Cheat Sheet
·3 mins
Blog En
Common tmux commands Cheat Sheet
FastAPI: Mock S3 with Moto
·3 mins
Blog En AWS Backend Testing FastAPI
FastAPI Testing: Mock AWS S3 Boto3 With Moto
k8s: Extract Configmap or Secret to Env File
·2 mins
Blog En Devops Kubernetes
Kubernetes Cheat Sheet: Extract ConfigMap or Secret to .env file
NCKU CSIE Freshman First Semester
·5 mins
Blog En
What did I do in the first semester of freshman year?