File (Flat) Handling in Python
Types of files in python:
1: Text file: Stores data in the form of characters. Customarily used to store text/string data.
2: Binary file: Stores data in the form of bytes. It can be used to store text, images, audio and video.
Open() Function:
To open a file, we use the open() function. Here we need to mention 'filename' and 'mode' in which we want to open that file.
Syntax: File Handler = open("FileName", "Mode")
Mode: w (write), r(read), a(append) etc.
A file that is opened should be closed with the help of the close() function.
To write in a file, we use the write() function.
Example:
A simple Python program to open, write, read and close a file.
# Open a file in write mode
f = open("myFile.txt","w")
# Take input from user
str = input("Enter text: ")
f.write(str) # Write the string into file
f.close() # Close the file
# Again open the file in read mode
print("Now Reading that file....")
f = open("myFile.txt","r")
str = f.read() # Read from file
# Display the content on the screen
print(str)
f.close() # Close The file
Thank You!