The best way to Learn a File in Python


If it’s worthwhile to learn a file in Python, then you should use the open() built-in perform that will help you.

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

Hey, it is a take a look at file
With some contents

The best way 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 can print out the contents of the file.

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

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

The best way to Solely Learn Components of a File in Python

For those who don’t need 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))

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

The best way to Learn Traces from a File in Python

If it’s worthwhile to learn every line of a file in Python, then you should use the readline() perform:

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

For those who known as this twice, then it might 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 via the file:

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

The best way to Shut a File in Python

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

It’s because the open() technique, will hold 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