Day 10: Files I/O
Tags: tutorial, beginners, python, programming
Published: 2023-02-23 08:00:24


## What I learnt

- Files
- Open a file
- Context Manager
- Reading and writing files using the context manager
- Reading contents of a file in chunks
- Copying a file
- File paths in different operating systems

## Files

File I/O is the process of reading and writing to files to disk storage or your computer programmatically. There is a high probability that you will need to read and write to files in your Python projects.

## Open a file

To open a file, we use the open() function. The open() function takes two parameters; filename, and mode.

Usually, when a file is opened, it is opened in the same directory as the Python file. However, you can specify the path to the file if it is not in the same directory.

There are four different methods (modes) for opening a file:

- "r" - Read - Default value. Opens a file for reading, error if the file does not exist

- "a" - Append - Opens a file for appending, creates the file if it does not exist

- "w" - Write - Opens a file for writing, creates the file if it does not exist

- "x" - Create - Creates the specified file, returns an error if the file exists

### Example

```python
# Open a file
my_file = open('sample.txt', 'r')
print(my_file.name) # sample.txt
print(my_file.mode) # prints mode of file
my_file.close()
```

## Read a file

To read a file, we use the read() method. The read() method returns the whole text, but you can also specify how many characters you want to return.

> NOTE: When you are done working with a file, it is a good practice to close it. This can be done by using the close() method.

### Example

```python
# Read a file
my_file = open('sample.txt', 'r')
print(my_file.read()) # prints contents of file
my_file.close()
```

## Context Manager

The context manager is a way to open a file and close it automatically. This is done by using the with statement. This is the preferred way to open a file and the most commonly used method.

### Example

```python
with open('sample.txt', 'r') as file:
    print(file.read()) # prints contents of file
    print(file.read(10)) # prints first 10 characters of file
    print(file.readline())  # prints first line of file
    print(file.readlines()) # prints all lines of file as a list
    for line in file:
        print(line, end='') # prints each line of file
```

Usually, when using the context manager, you don't need to close the file using the `close()` method because it is done automatically.
However, if you want to close the file, you can do so by using the `close()` method.

## Reading and writing files using the context manager

- Read a file
  The read() method returns the whole text, but you can also specify how many characters you want to return.
  Also, there is a readline() method that returns one line, and a readlines() method that returns a list of lines in the file.

### Example

```python

with open('sample.txt', 'r') as file:
    print(file.read())  # prints contents of file
    print(file.read(10))  # prints first 10 characters of file
    print(file.readline())  # prints first line of file
    print(file.readlines())  # prints all lines of file as a list
    for line in file:
        print(line, end='')
    file.seek(0)  # resets the cursor to the beginning of the file
    print(file.tell())  # returns the position of the cursor (in bytes
    print(file.read())
```

- Append to a file
  To append to a file, you need to open the file in append mode. The append mode is 'a'. When you append into a file, the cursor is at the end of the file. So, if you want to append to the beginning of the file, you need to reset the cursor to the beginning of the file.

```python

with open('sample.txt', 'a') as file:

file.write('You could also append to the file. \n')
```

- Read and Write to a file
  To read and write to a file, you need to open the file in read and write mode. The read and write mode is 'r+'.

```python

with open('sample.txt', 'r+') as file:

print(file.read())

file.write('This is a new line!!')
```

- Write to a file (Create a file)

```python

with open('new_file.txt', 'w') as file:
    file.write('This is a new file')
```

### Exercise:

- Write a program to read a text file and print its contents line by line.

```python
with open('test.md', 'r') as file:
    for line in file:
        print(line, end='')
```

## Reading contents of a file in chunks

    When you are reading a file (especially large files). You can read each file in chunks and process the chunks. This is more efficient than reading the whole file at once.

```python

with open('test.md', 'r') as file:
    chunk_size = 20
    content = file.read(chunk_size)
    while len(content) > 0:
        print(content, end='')
        content = file.read(chunk_size) # reads next chunk of file and this continues until the end of the file
```

## Copying a file

        To copy a file, you need to open the file in read mode and open the new file in write mode. Then, you can read the contents of the file and write it to the new file.

```python
with open('test.md', 'r') as rf:
    with open('test_copy.md', 'w') as wf:
        for line in rf:
            wf.write(line)
```

## Copying a file in chunks

```python
with open('test.md', 'r') as rf:
    with open('test_copy.md', 'w') as wf:
        chunk_size = 20
        content = rf.read(chunk_size)
        while len(content) > 0:
            wf.write(content)
            content = rf.read(chunk_size)
```

## File paths in different operating systems

The files for our operating systems are different or slightly different from each other.
In Windows, the file path is separated by a backslash (\) while in Linux and Mac OS, the file path is separated by a forward slash (/).
To make sure that your code works in different operating systems, you need to use the python `os` module.

## File paths

A file path is a string that represents the location of a file. There are two types of file paths; absolute file path and relative file path.

- Absolute file path
  An absolute file path is a file path that starts from the root folder. The root folder is the folder that contains all the other folders in your computer. The root folder is usually named C:\ on Windows and / on Linux and Mac.

```python
## Absolute file path
# Linux and Mac OS

with open('C:/Users/Dummy/Documents/test.md', 'r') as file:
        print(file.read())

#  Windows OS
with open('C:\\Users\\Dummy\\Documents\\test.md', 'r') as file:
    print(file.read())
```

- Relative file path
  A relative file path is a file path that is relative to the current working directory. The current working directory is the folder that contains the Python file that you are running.

```python
  # Relative file path
with open('test.md', 'r') as file:
    print(file.read())
```

## Conclusion

In this article, I shared what I learnt with File Objects and also how to manipulate files in Python.

I hope you found this article helpful. If you have any questions, please leave a comment below.
I'd love to hear from you, and please share this post with your friends and follow me on my journey here on [Dev.to](https://dev.to/jobizil) for more articles like this.
Thank you for taking the time to read this.