Understanding 11 Important Python File Handling Methods
Tags: python, beginners, codenewbie, programming
Published: 2021-08-14 00:10:42

Hi, I'm [Aya Bouchiha](developer.aya.b@gmail.com), today, we'll talk about 11 important python file handling methods.

## close

+ **close()**: helps you to close an opened file.

```python
test_file = open('test.txt', 'r')
first_line = test_file.readline()
# do something...

test_file.close()
```

There is another method to close a file, that works automaticly without using close method:

```python
with open('test.txt', 'r') as test_file:
    first_line = test_file.readline()
    # do something

```

## readable

+ **readable()**: checks if a specified file is readable.

```python
with open('test.txt', 'w') as test_file:
    print(test_file.readable()) # False
    print(test_file.readline()) # error
    
with open('test.txt', 'r') as test_file:
    print(test_file.readable()) # True
```

## read

+ **read(size= -1)**: returns the given number of bytes (by default -1)  from a specified file. 

test.txt
```
Hello, I'm Aya Bouchiha
This is an Example
Aya Bouchiha
Test
```

index.py
```python
with open('test.txt', 'r') as test_file:
    
    print(test_file.read(28))
    # Hello, I'm Aya Bouchiha
    # This

    print(test_file.read())
    #  is an Example
    # Aya Bouchiha
    # Test

    print(test_file.read())
    # ""
```

## readline

+ **readline(*size=-1*)**: used to read a given number of bytes (by default = -1) in a line from a specified file. 

test.text:
```
Hello, I'm Aya Bouchiha
This is an Example
Aya Bouchiha
Test
```

index.py:
```python
with open('test.txt', 'r') as test_file:
    first_line = test_file.readline() 
    second_line = test_file.readline() 
    fname_from_third_line = test_file.readline(3)
    
    print(first_line) # Hello, I'm Aya Bouchiha
    print(second_line) # This is an Example
    print(fname_from_third_line) # Aya
```

## readlines

+ **readlines(N = -1)**: returns all file lines as a list. N parameter is used  to limit the number of lines returned. If the total number of bytes returned exceeds the specified number, no more lines are returned.

for more details:
+ [w3schools](https://www.w3schools.com/python/ref_file_readlines.asp#:~:text=The%20readlines()%20method%20returns,no%20more%20lines%20are%20returned.)
+ [stackoverflow](https://stackoverflow.com/questions/14541010/pythons-function-readlinesn-behavior)

user.txt:
```
Aya Bouchiha
developer.aya.b@gmail.com
https://t.me/AyaBouchiha
```

index.py:
```py
with open('user.txt', 'r') as user_file:
    # [
    #  "Aya Bouchiha\n",
    #  "developer.aya.b@gmail.com\n",
    #  "https://t.me/AyaBouchiha\n",
    # ]
    print(user_file.readlines())

    user_file.seek(0)

    print(user_file.readlines(3))
    # ["Aya Bouchiha\n"]
```

## seek, tell

+ **seek(pos)**: helps you to specifiy the cursor's position, and gets the new one. [more details](https://www.geeksforgeeks.org/python-seek-function/)

+ **tell()**: lets you get the file's current position.

test.text:
```
Hello, I'm Aya Bouchiha
This is an Example
Aya Bouchiha
Test
```

index.py:
```python
with open('test.txt', 'r') as test_file:
    print(test_file.tell()) # 0
    first_line = test_file.readline()  # Hello, I'm Aya Bouchiha
    current_position = test_file.seek(7) # "hello, " is ignored, len("hello, ") is 7
    print(current_position) # 7
    print(test_file.tell()) # 7
    print(test_file.read())
    # I'm Aya Bouchiha
    # This is an Example
    # Aya Bouchiha
    # Test
```

## writable

+ **writable()**: checks if the specified file is writable.

```python
with open('test.txt', 'r') as test_file:
    print(test_file.readable()) # True
    print(test_file.writable()) # False

with open('test.txt', 'w+') as test_file:
    print(test_file.readable()) # True
    print(test_file.writable()) # True
```

## write

+ **write(value)**: lets you write a given value in a specified file.

message.txt:
```
```

index.py:
```python
with open('message.txt', 'w') as message_file:
    message = 'Good morning!'
    message_file.write(message)
```

message.txt:
```
Good morning!
```

## writelines

+ **writelines(sequence)**: used to write a sequence of items in a specified file.[more details](https://www.tutorialspoint.com/python/file_writelines.htm)

#### Example 1:

emails.txt:
```
```

index.py:
```py
emails = ["developer.aya.b@gmail.com\n", "john.doe@gmail.com",]
with open('emails.txt', 'w') as emails_file:
    emails_file.writelines(emails)
```

emails.txt:
```
developer.aya.b@gmail.com
john.doe@gmail.com
```

#### Example 2:
admins.txt:
```
```

index.py:
```python
admins = ["Aya Bouchiha\n", "John Doe\n", "Simon Spouf"]

with open('admins.txt', 'a+') as admins_file:

    print(admins_file.readable()) # True
    print(admins_file.writable()) # Trye
    
    admins_file.write("Hi, welcome to admins.txt\n")
    admins_file.write('admins are:\n')

    admins_file.writelines(admins)
    
    print(admins_file.tell()) # 75
    admins_file.seek(0)
    print(admins_file.read())
    # Hi, welcome to admins.txt
    # admins are:
    # Aya Bouchiha
    # John Doe
    # Simon Spouf
```

admins.txt:
```
Hi, welcome to admins.txt
admins are:
Aya Bouchiha
John Doe
Simon Spouf
```


## truncate

+ **truncate(size)**: lets you truncate the file size.

#### Example 1:

emails.txt:
```
developer.aya.b@gmail.com
john.doe@gmail.com
```

```python
with open('emails.txt', 'a+') as emails_file: 

    email_address = 'developer.aya.b@gmail.com'

    emails_file.truncate(len(email_address))

    emails_file.seek(0)
    
    # developer.aya.b@gmail.com
    print(emails_file.read())

```

emails.txt:
```
developer.aya.b@gmail.com
```

#### Example 2:

emails.txt:
```
```

index.py:
```py
with open('emails.txt', 'a+') as emails_file: 

    emails = [
        "developer.aya.b@gmail.com\n",
        "john.doe@gmail.com\n",
        "someone.d@gmail.com"
    ]

    emails_file.writelines(emails)

    emails_file.seek(0)
    
    # developer.aya.b@gmail.com
    print(emails_file.readline()) 

    emails_file.truncate(len("".join(emails[:2])))

    emails_file.seek(0)

    # developer.aya.b@gmail.com
    # john.doe@gmail.com
    print(emails_file.read())

    emails_file.seek(len(emails[0]))

    # size = cursor's position which is len(emails[0])
    emails_file.truncate() 

    # 26
    print(emails_file.tell()) 
    
    emails_file.seek(0)

    # developer.aya.b@gmail.com
    print(emails_file.read())
```

emails.txt:
```
developer.aya.b@gmail.com

```

## Summary

+ **close()**:  closes an opened file.
+ **readable()**: checks if a specified file is readable.
+ **read(size= -1)**: returns the given number of bytes (by default -1)  from a specified file. 
+ **readline(*size=-1*)**: reads a given number of bytes (by default = -1) in a line from a specified file. 
+ **readlines(N = -1)**: returns all file lines as a list.
+ **seek(pos)**: specifiy the cursor's position, and returns the new one.
+ **tell()**: returns the file's current position.
+ **writable()**: checks if the specified file is writable.
+ **write(value)**:  writes a given value in a specified file.
+ **writelines(sequence)**:  writes a sequence of items in a specified file.
+ **truncate(size)**: truncates the file size.

### References & Useful Resources

#### Articles
+ [https://www.programiz.com/python-programming/file-operation](https://www.programiz.com/python-programming/file-operation)
+ [https://www.w3schools.com/python/python_file_handling.asp](https://www.w3schools.com/python/python_file_handling.asp)
+ [https://www.geeksforgeeks.org/file-handling-python/](https://www.geeksforgeeks.org/file-handling-python/)
+ [https://www.tutorialspoint.com/python/python_files_io.htm](https://www.tutorialspoint.com/python/python_files_io.htm)
+ [https://www.w3schools.com/python/python_ref_file.asp](https://www.w3schools.com/python/python_ref_file.asp)

#### Youtube Videos
+ [https://www.youtube.com/watch?v=aequTxAvQq4](https://www.youtube.com/watch?v=aequTxAvQq4)
+ [https://www.youtube.com/watch?v=Uh2ebFW8OYM](https://www.youtube.com/watch?v=Uh2ebFW8OYM)
+ [https://www.youtube.com/watch?v=ixEeeNjjOJ0](https://www.youtube.com/watch?v=ixEeeNjjOJ0)
+ [https://www.youtube.com/watch?v=b9rSczloSeA](https://www.youtube.com/watch?v=b9rSczloSeA)



### Suggested Posts

+ [All You Need To Know About Python JSON Module](https://dev.to/ayabouchiha/all-you-need-to-know-about-python-json-module-5ef0)

+ [Youtube Courses, Projects To Learn Javascript](https://dev.to/ayabouchiha/youtube-courses-projects-to-master-javascript-3lhc)

+ [part-1: 5 Useful Python String Methods](https://dev.to/ayabouchiha/5-useful-python-string-methods-4pe7)

+ [5 Helpful Python Math Module Methods](https://dev.to/ayabouchiha/5-helpful-python-math-module-methods-44gf)


To Contact Me:

email: developer.aya.b@gmail.com

telegram: [Aya Bouchiha](https://t.me/AyaBouchiha)

Hope you enjoyed reading this post :)