使用asyncio库进行并发文件读写操作的实例代码
发布时间:2024-01-02 07:39:14
下面是一个使用asyncio库进行并发文件读写操作的实例代码:
import asyncio
async def read_file(file_path):
print(f'Reading file: {file_path}')
with open(file_path, 'r') as file:
content = file.read()
await asyncio.sleep(1) # 模拟读取文件的耗时操作
print(f'{file_path} content: {content}')
async def write_file(file_path, content):
print(f'Writing file: {file_path}')
with open(file_path, 'w') as file:
file.write(content)
await asyncio.sleep(1) # 模拟写入文件的耗时操作
print(f'{file_path} was written successfully')
async def main():
tasks = [
read_file('file1.txt'),
read_file('file2.txt'),
write_file('file3.txt', 'Hello, World!'),
write_file('file4.txt', 'This is a test'),
]
await asyncio.gather(*tasks)
if __name__ == '__main__':
asyncio.run(main())
在上面的例子中,我们定义了两个异步函数read_file和write_file,分别用于读取和写入文件的操作。这两个函数内部都模拟了一个耗时的操作,使用asyncio.sleep(1)使其等待1秒钟来模拟读取和写入文件的耗时过程。
在main函数中,我们定义了一组任务,包括读取file1.txt和file2.txt的内容,以及将Hello, World!和This is a test写入file3.txt和file4.txt。然后,我们使用asyncio.gather函数来并发地执行这些任务。
最后,我们使用asyncio.run来运行main函数。
通过使用asyncio库,我们可以方便地实现并发的文件读写操作,提高程序的运行效率。
