Understanding 11 Important Python File Handling Methods

Hi, I’m Aya Bouchiha, today, we’ll talk about 11 important python file handling methods.

close

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

test_file = open(‘test.txt’, ‘r’)
first_line = test_file.readline()
# do something…

test_fil…


This content originally appeared on DEV Community and was authored by Aya Bouchiha

Hi, I'm Aya Bouchiha, today, we'll talk about 11 important python file handling methods.

close

  • close(): helps you to close an opened file.
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:

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

readable

  • readable(): checks if a specified file is readable.
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

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:

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:

user.txt:

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

index.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

  • 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:

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.
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:

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

Example 1:

emails.txt:

index.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:

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
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:

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

Youtube Videos

Suggested Posts

To Contact Me:

email: developer.aya.b@gmail.com

telegram: Aya Bouchiha

Hope you enjoyed reading this post :)


This content originally appeared on DEV Community and was authored by Aya Bouchiha


Print Share Comment Cite Upload Translate Updates
APA

Aya Bouchiha | Sciencx (2021-08-14T00:10:42+00:00) Understanding 11 Important Python File Handling Methods. Retrieved from https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/

MLA
" » Understanding 11 Important Python File Handling Methods." Aya Bouchiha | Sciencx - Saturday August 14, 2021, https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/
HARVARD
Aya Bouchiha | Sciencx Saturday August 14, 2021 » Understanding 11 Important Python File Handling Methods., viewed ,<https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/>
VANCOUVER
Aya Bouchiha | Sciencx - » Understanding 11 Important Python File Handling Methods. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/
CHICAGO
" » Understanding 11 Important Python File Handling Methods." Aya Bouchiha | Sciencx - Accessed . https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/
IEEE
" » Understanding 11 Important Python File Handling Methods." Aya Bouchiha | Sciencx [Online]. Available: https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/. [Accessed: ]
rf:citation
» Understanding 11 Important Python File Handling Methods | Aya Bouchiha | Sciencx | https://www.scien.cx/2021/08/14/understanding-11-important-python-file-handling-methods/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.