If you have to learn a file in Python, then you should utilize the open()
built-in perform that will help you.
Let’s say that you’ve got a file referred to as somefile.txt
with the next contents:
Good day, it is a check file
With some contents
Tips on how 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 unique location, then we’d specify the situation as effectively:
f = open("/some/location/somefile.txt", "r")
print(f.learn())
Tips on how to Solely Learn Components 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 simply do need.
f = open("somefile.txt", "r")
print(f.learn(5))
It will specify what number of characters you need to return from the file.
Tips on how to Learn Strains from a File in Python
If you have to 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 could learn the primary two traces:
f = open("somefile.txt", "r")
print(f.readline())
print(f.readline())
A greater method to do that, is to loop via the file:
f = open("somefile.txt", "r")
for x in f:
print(x)
Tips on how to Shut a File in Python
It’s at all times good observe to shut
a file after you have 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()