Tags
python
Asked 2 years ago
12 Aug 2021
Views 246
Pearline

Pearline posted

How do you read a file in Python ?

How do you read a file in Python ?
iptracker

iptracker
answered Aug 17 '21 00:00

simple two step to read file in Python :
1. open file with open() method , open() method return file object

fp=open("path of the file")

open(file path) take file path as argument .
as you see above we store the open() method return object to another variable for later use.
alternatively open(filename, mode) , the open method has a second argument as "r" - read mode or 'w' - write mode

fp=open("path of the file","r")

we need here read mode so we passed 'r' as the second argument. if not pass anything as a second argument then it takes default as 'r' - read mode for the file open method.

2. read the opened file with read() method , read() method invoked by file object

data=fp.read()

read() method return full file data.
alternatively readline() method return one line per method call

3. after completion of the read file, close the file object

fp.close()

close() method release the file object

Python code to read a file :

fp=open("readfile.py")
data=fp.read()
fp.close()
pratik

pratik
answered Aug 17 '21 00:00




memory efficient , fast , and simple Python code to read a file :

fp=open("stock.csv")
for line in fp:
	print(line, end='')
fp.close()


simply iterate the file object with for loop to get each line of the file, it will read every line of the file and return it.
Post Answer