Example : A Python program to create a new or blank file to store some contents.
In Python, a file can be created in several ways by opening it in write ('w'), append ('a'), or exclusive ('x') mode using the open() function.
----------------------- OR ----------------------
file1 = open("sample.txt", "w")
file1.write("India is my glorious country.")
file1.close()
NB : It will create a new file if it does not exist otherwise overwrites the file if it already exists.
----------------------- OR ----------------------
file1 = open("sample.txt", "a")
file1.write("The capital of India is New Delhi.")
file1.close()
NB : It will create the file if it does not exist and adds data at the end of file if file already exists.
----------------------- OR ----------------------
with open("sample.txt", "w") as file1:
file1.write("India is my glorious country.")
NB:This method also creates a new file and also automatically closes the file.
----------------------- OR ----------------------
open("sample.txt", "w").close()
NB:This method creates a new empty or blank file.
----------------------- OR ----------------------
file1 = open("sample.txt", "x")
file1.write("India is my glorious country.")
file1.close()
NB : This method also creates a new file with some contents in exclusive mode but raises error if file already exists.
----------------------- OR ----------------------
TO CHECK THE CREATED FILE EXISTENCE
import os
if os.path.exists("sample.txt"):
print("File created successfully")
Example : A Python program to Read the stored contents.
file1 = open("sample.txt", "r")
content = file.read()
print(content)
file1.close()
NB : Here, read() reads the entire file content at once and file pointer moves to the end
----------------------- OR ----------------------
![]()
0 Comments