HomeSoftware EngineeringFind out how to Learn a File in Python

Find out how to Learn a File in Python


If it is advisable learn a file in Python, then you should utilize the open() built-in perform that can assist you.

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

Hiya, it is a check file
With some contents

Find out how to Open a File and Learn it in Python

We are able to learn the contents of this file as follows:

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

This may print out the contents of the file.

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

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

Find out how to Solely Learn Elements of a File in Python

In the event you don’t need to learn and print out the entire file utilizing Python, then you possibly can specify the precise location that you just do need.

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

This may specify what number of characters you need to return from the file.

Find out how to Learn Strains from a File in Python

If it is advisable learn every line of a file in Python, then you should utilize the readline() perform:

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

In the event you referred to as this twice, then it might learn the primary two strains:

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

A greater means to do that, is to loop by way of the file:

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

Find out how to Shut a File in Python

It’s at all times good follow to shut a file after you’ve opened it.

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

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

Most Popular

Recent Comments