Methods to Learn a File in Python


If that you must learn a file in Python, then you should utilize the open() built-in operate that will help you.

Let’s say that you’ve a file known as somefile.txt with the next contents:

Hi there, this can be a check file
With some contents

Methods to Open a File and Learn it in Python

We will learn the contents of this file as follows:

f = open("somefile.txt", "r")
print(f.learn())

It will print out the contents of the file.

If the file is in a distinct location, then we might specify the placement as properly:

f = open("/some/location/somefile.txt", "r")
print(f.learn())

Methods to Solely Learn Elements of a File in Python

Should you don’t wish to learn and print out the entire file utilizing Python, then you may specify the precise location that you simply do need.

f = open("somefile.txt", "r")
print(f.learn(5))

It will specify what number of characters you wish to return from the file.

Methods to Learn Traces from a File in Python

If that you must learn every line of a file in Python, then you should utilize the readline() operate:

f = open("somefile.txt", "r")
print(f.readline())

Should you known as this twice, then it will learn the primary two traces:

f = open("somefile.txt", "r")
print(f.readline())
print(f.readline())

A greater manner to do that, is to loop by the file:

f = open("somefile.txt", "r")
for x in f:
  print(x)

Methods to Shut a File in Python

It’s all the time good follow to shut a file after you’ve got opened it.

It’s because the open() technique, will preserve a file handler pointer open to that file, till it’s closed.

f = open("somefile.txt", "r")
print(f.readline())
f.shut()

Leave a Reply