A Beginner's Guide to File Input/Output (I/O) in Python
Tags: beginners, programming, python
Published: 2023-09-24 17:48:09

Python is a versatile and powerful programming language that offers a range of functionalities, one of which is handling files. In this guide, we'll explore the basics of File Input/Output (I/O) in Python, focusing on the open method and file modes ('r', 'a', and 'w').

## The 'open' Function
The open function gives you the ability to interact with files in Python. It's used to open files and create a file object, which allows you to read, write, or append content.

```
file = open("things_i_wrote.txt", "w")
file.write("Text I'm writing")
file.close()
```

The first argument to open is the file path, and the second argument is the mode in which you want to open the file. The .close() method is effectively a "save" button when writing into files.

## Closing Files Automatically with a Context Manager (with)
To ensure that files are properly closed after you're done with them, it's good practice to use a context manager. This will automatically close the file when you're done with it, allowing for more compact code. The same code block above can be rewritten like this:

```
with open("things_i_wrote.txt", "w") as file:
    file.write("Text I'm writing")
```


## Modes in File I/O


**Writing ('w' mode)**
The 'w' mode is used for writing to files. If the file exists, the new content that is to be written will be written over the already existing file. If not, a new file will be created. Be careful, as this can potentially overwrite existing content.

```
thing_to_write = input("What would you like to write? ")

with open("things_i_wrote.txt", 'w') as file:
    file.write(thing_to_write)
```

![terminal block](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wvta9b273e8ieqhzzldz.png)


![txt file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w2eeb7bidpe98t3uygyl.png)

In the example above, we have written code to collect user input from the terminal and write the input into a .txt file. You'll notice that after inputing "Thing 1", "Thing 2", and "Thing 3" to the .txt file, only "Thing 3" appears in the file. This is because the file was rewritten three different times with the last rewrite being "Thing 3". In order to get around this, we will instead use the 'a' mode and append the content into the .txt file.

**Appending ('a' mode)**
The 'a' mode is used for appending content to the end of an existing file. It's useful when you want to add data without overwriting the original content.

```
thing_to_write = input("What would you like to write? ")

with open("things_i_wrote.txt", 'a') as file:
    file.write(f"{thing_to_write}\n")
```

![terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dnj2tyjcmtxtd055ihk.png)


![text file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ntv19iirv2cu1xz9y13.png)

As you can see, we were able to successfully write all of our user inputs into our .txt file by appending the inputs rather than writing them. If you're wondering what the "\n" is, this combination of symbols is an indicator for the computer that the end of the input starts a new line in the file. If we omitted the "\n", the file would look like this:


![file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8snz0fuufegczqgib2h2.png)

**Reading ('r' mode)**

The 'r' mode is used for reading files. It's the default mode when no mode is specified, so it is not necessary to write. When you open a file in read mode, you can only read the content and not modify it, but it allows you to collect data and save them into variables for your program. 

```
extracted_from_file = []

with open("things_i_wrote.txt") as file:
    for line in file:
        extracted_from_file.append(line.rstrip())

print(extracted_from_file)
```


![terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0zkp6i07a4asfqbhfc3.png)

Say we never created and wrote the .txt file that we've been using previously. If we were to want to extract information from a file, we can use the "r" mode in Python to read and extract that data. We've omitted the "r" because the open() method is set to read by default. We are able to create a list variable, read through the .txt file, and save the content of the file in the list variable. We also used .rstrip() to strip the "\n" characters so they aren't saved into the list. If we neglected to add .rstrip(), the list would look like this:


![terminal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bp775rytbl4fvjb08z6.png)


## Conclusion
File I/O is a fundamental aspect of programming. With the open method and different modes ('r', 'a', and 'w'), you can read, write, and append content to files in Python. Remember to use a context manager ("with") for safe file handling. With more knowledge on handling files, a programmer can have the ability to manipulate audio files, image files, and much more. 

Sources:
https://www.w3schools.com/python/ref_func_open.asp

https://docs.python.org/3/tutorial/inputoutput.html