Tags
python
Asked 2 years ago
12 Aug 2021
Views 203
Eusebio

Eusebio posted

How do I save and read a file in Python ?

How do I save and read a file in Python ?
chirag

chirag
answered Aug 17 '21 00:00

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


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


as you see above, the open() method returns file object which is saved 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


we need here write mode so we passed 'w' 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. write content into the opened file with write() method, write() method invoked by a file object


fp.write("information is the key"
)

write() method write the content into the file .


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


fp.close()


close() method release the file object and release the memory

Python code to write the content into the file :

fp=open("test.txt","w")
fp.write("information is the key")
fp.close()


simple two-step to read the 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 a 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


Final code to write and read the file in Python is as belowed :

#file write Python code
fp=open("test.txt","w")
fp.write("information is the key")
fp.close()
#file read Python code
fp=open("test.txt")
filecontent=fp.read()
fp.close()


refrence by : https://arrayoverflow.com/question/how-do-you-read-a-file-in-python/3163
Post Answer