Tags
python
Asked 3 years ago
12 Aug 2021
Views 329
Milton

Milton posted

How do I open and read a file in Python ?

How do I open and read a file in Python ?
jassy

jassy
answered Oct 5 '21 00:00

use the with keyword open file with open() function, and it will return file object.
file object have read() function is used to read file.

with open('info.txt') as f:
	read_data = f.read()
f.closed
print(read_data)


file object refrernce.closed will close the file.
jaydeep

jaydeep
answered Oct 5 '21 00:00

open(filename) is used to open file in Python.
open() method should have file name as argument.
open() method return file refrence which used to read or write to file.
read() function read the file content.read() function can be called by file refrence.
b] read() [/b] function close the file and release the file object from the memory.it's good to clean the resource.


fp=open('any file full name with extension with correct path here')
filecontent=fp.read()
fp.close()
print(filecontent)// do what you feel good with file content
Post Answer