Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
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
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())
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.
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)
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()