Asynchronous File I/O: `aiofiles`
We've seen how asyncio is perfect for I/O-bound tasks and how aiohttp solves the problem of blocking network requests. But what about the other major type of I/O: reading and writing files?
We've seen how asyncio is perfect for I/O-bound tasks and how aiohttp solves the problem of blocking network requests. But what about the other major type of I/O: reading and writing files?
In the last article, we learned how to open files using different modes. Now, let's focus on the primary reason you'd open a file in read mode ('r'): to get data out of it. Python's file objects provide several methods for reading content, each suited for different situations.
Throughout our articles on file I/O, we've consistently used a specific structure block. We mentioned that it's the "modern, safe, and recommended" way to handle files, but we haven't explained why.
When we work with files, we often hardcode the file path as a simple string, like 'myfolder/myfile.txt'. This works, but it's not robust. What happens if your script is run on a different operating system? Windows uses a backslash (\) as a path separator, while macOS and Linux use a forward slash (/). Hardcoding paths with one type of slash can make your script fail on other systems.
So far, our Python programs have been self-contained. They run, perform calculations, and when they finish, any data they generated is gone. To create persistent programs that can save data and read it back later, we need to interact with files.
We've mastered the art of reading from files. Now it's time to look at the other side of the coin: writing data to files. This is how you can save program state, log events, generate reports, or create any text-based output you need.