Python File Closing Method
A file which is opened should be closed using the close() method. Once a file is opened but not closed, then the data of the file may be corrupted or deleted in some cases. Also, if the file is not closed, the memory utilized by the file is not freed, leading to problems like insufficient memory. This happens when we are working with several files simultaneously. Hence it is mandatory to close the file.
we are creating a file where we want to store some characters. We know that a group of characters represent a string. After entering a string from the keyboard using input() function, we store the string into the file using write() method as:
Python Program with File Closing Method
Below python program to create a text file to store individual characters and close the File
#creating a file to store characters #open the file for writing data f = open('myfile.txt', 'w') str = input('Enter text:') f.write(str) f.close()
A Python program to create a text file to store individual characters.
f = open('myfile.txt', 'w')
str = input('Enter text:')
The next step is to read the data from 'myfile.txt' and display it on the monitor. To read data from a text file, we can use read() method as:
str = f.read()
This will read all characters from the file 'f' and returns them into the string 'str'. We can also use the read() method to read only a specified number of bytes from the file as:
str = f.read(n)
where 'n' represents the number of bytes to be read from the beginning of the file.
Python Program to Read a File
#reading characters from file #open the file for reading data f = open('myfile.txt', 'r') #read all characters from file str = f.read() #display them on the screen print(str) #closing the file f.close()