Here are 10 Python snippets demonstrating how to perform asynchronous file I/O operations using the aiofiles library. Each snippet is separated by a delimiter.
Snippet 1: Writing to a File Asynchronously
Copy
import aiofiles
import asyncio
async def write_file():
async with aiofiles.open("example.txt", mode="w") as f:
await f.write("Hello, World!")
asyncio.run(write_file())
Snippet 2: Reading a File Asynchronously
Copy
import aiofiles
import asyncio
async def read_file():
async with aiofiles.open("example.txt", mode="r") as f:
content = await f.read()
print(content)
asyncio.run(read_file())
Snippet 3: Appending to a File Asynchronously
Copy
Snippet 4: Reading a File Line by Line Asynchronously
Copy
Snippet 5: Writing JSON Data Asynchronously
Copy
Snippet 6: Reading JSON Data Asynchronously
Copy
Snippet 7: Copying File Contents Asynchronously
Copy
Snippet 8: Checking File Existence Asynchronously
Copy
Snippet 9: Asynchronous File Deletion
Copy
Snippet 10: Asynchronous File Writing with Buffering
import aiofiles
import asyncio
async def append_file():
async with aiofiles.open("example.txt", mode="a") as f:
await f.write("\nThis is appended text.")
asyncio.run(append_file())
import aiofiles
import asyncio
async def read_lines():
async with aiofiles.open("example.txt", mode="r") as f:
async for line in f:
print(line.strip())
asyncio.run(read_lines())
import aiofiles
import asyncio
import json
async def write_json():
data = {"name": "Alice", "age": 30}
async with aiofiles.open("data.json", mode="w") as f:
await f.write(json.dumps(data))
asyncio.run(write_json())
import aiofiles
import asyncio
import json
async def read_json():
async with aiofiles.open("data.json", mode="r") as f:
content = await f.read()
data = json.loads(content)
print(data)
asyncio.run(read_json())
import aiofiles
import asyncio
async def copy_file(src, dest):
async with aiofiles.open(src, mode="r") as source:
content = await source.read()
async with aiofiles.open(dest, mode="w") as destination:
await destination.write(content)
asyncio.run(copy_file("example.txt", "example_copy.txt"))
import aiofiles
import asyncio
async def buffered_write():
async with aiofiles.open("buffered.txt", mode="w") as f:
for i in range(10):
await f.write(f"Line {i}\n")
asyncio.run(buffered_write())