利用io.BufferedRandom()实现文件读写的进度条显示方法
发布时间:2023-12-29 12:51:57
使用io.BufferedRandom()实现文件读写的进度条显示方法可以通过在每次读写数据时更新进度条,并将进度条打印到控制台上。以下是一个示例代码:
import io
import time
def copy_with_progress(src_file, dst_file):
CHUNK_SIZE = 1024 # 每次读写的块大小
total_size = src_file.seek(0, io.SEEK_END) # 获取源文件的总大小
src_file.seek(0) # 重新将文件指针指向文件开头
bytes_copied = 0
progress = 0
with io.BufferedRandom(dst_file) as buffered_dst:
while True:
chunk = src_file.read(CHUNK_SIZE)
if not chunk:
break # 读取完毕
buffered_dst.write(chunk)
bytes_copied += len(chunk)
# 更新进度条
progress = int(bytes_copied * 100 / total_size)
print(f"\rCopying... {progress}% ", end="")
time.sleep(0.1) # 适当的延时,避免显示过快
print("
Copy completed!")
# 使用示例
with open("source_file.txt", "rb") as src_file, \
open("destination_file.txt", "wb") as dst_file:
copy_with_progress(src_file, dst_file)
上述示例代码定义了一个copy_with_progress()函数,该函数接受一个源文件和目标文件作为参数。在函数中,通过先获取源文件的总大小,然后在每次写入数据后更新进度条,直到文件全部复制完毕。
在主程序中,通过打开源文件和目标文件,并将它们作为参数传递给copy_with_progress()函数来复制文件。函数会在进度条更新时,每隔0.1秒打印到控制台上。
