I am writing data to a new file. I am reading data from flask request(uploading a file) but during writing I am providing option to cancel the writing, for that I have used process and event, and passing required arguments.
Read file
file = request.files.get("file")
method-1: contents = file.stream.read()
method-2: contents = file.stream.readlines()
For eg file as train.csv (10MB size)
Write file
def __init__(self, filename: str, contents: Any, read_length: int) -> bool:
file: Path = DIRPATH / self.filename
method-1:
with open(file, "wb") as fp:
write_length = fp.write(self.contents)
if self.event.wait(0.4):
break
Result for method-1: The entire file is getting written in one go and my cancel option becomes useless. But the writing speed is very fast, takes only few seconds
method-2:
with open(file, "wb") as fp:
for line in self.contents:
cnt = fp.write(line)
write_length += cnt
if self.event.wait(0.4):
break
else:
continue
Result for method-2: The entire file is getting written line by line and I am able to cancel the writting successfully but the writing speed is significantly slow, takes significant amount of miniutes.
Is there way to write good amount of chunks in file before waiting for event thereby making writing speed faster by using read() or readlines().