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.")
print("New file is created")
file1.close()

NB : It will create a new and seperate file named as 'sample.txt' with their contents if it does not exist already otherwise overwrites the previous file contents with new one if it already exists.
A separate file with source code only is also created with the name such as untitled.py.
Both the file is created in the same directory normally at users folder as path directed at terminal. 


file1 = open("d:\sample.txt", "w")   #creates file in D drive.
file1.write("India is my glorious country.")
print("New file is created")
file1.close()


file1 = open("sample1.txt", "w")
file1.write("India is my glorious country.\nBihar is my glorious state.\nPatna is my glorious town.")   # creates file with contents in next new lines.
print("New file is created")
file1.close()

-----------------------  OR  ----------------------

file1 = open("sample.txt", "a")
file1.write("The capital of India is New Delhi.")
print("The content is added to the existing file")
file1.close()

NB : It will even create the file if it does not exist already and adds data at the end of file without overwriting if file already exists.

-----------------------  OR  ----------------------

with open("sample1.txt", "w") as file1:
    file1.write("India is my glorious country.")
    print("File is created")

NB:This is another method to create a new file that automatically closes the file itself.

-----------------------  OR  ----------------------

open("sample.txt", "w").close()
print("File is created")

NB:This method creates a new empty or blank file only with no contents.

-----------------------  OR  ----------------------

file1 = open("sample.txt", "x")
file1.write("India is my glorious country.")
print("File is created")
file1.close()

NB : This method 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 already exists")
else:
    print("File does not exists")
Example : A Python program to read the stored contents from a file.
"rb" is used to read the binary files.

file1 = open("sample.txt", "r")
content = file.read() 
print(content)
file1.close()

NB : Here, read() method reads the entire file content at once and file pointer moves to the end.

-----------------------  OR  ----------------------

file1 = open("sample.txt", "r")
content = file1.readline()
print(content)
file1.close()

NB : Here, readline() method reads the file content line by line/one line at a time.

-----------------------  OR  ----------------------

file1 = open("sample.txt", "r")
content = file1.readlines()
for x in content:
    print(x)
file1.close() 

NB : Here, readlines() method reads all the lines of the file content at a time and give output as list of lines.

-----------------------  OR  ----------------------

with open("sample.txt", "r") as file1:
    for x in file1:
        print(x)

NB : This method is efficient to read large files and also automatically closes the file.
Example : A Python program to count the contents of a file.
file1 = open("sample.txt", "r")
print(file1.read(10))   # Reads first 10 characters with spaces.
file1.close()

-------------------  OR  -------------------

file1 = open("sample.txt", "r")
content = file1.read()
count = len(content)
print("Total number of characters in the file:", count)
file1.close()

-------------------  OR  -------------------

file1 = open("sample.txt", "r")
content = file1.read()
count = len(content.split())  #split() separates words based on whitespace.
print("Total number of words in the file:", count)
file1.close()

-------------------  OR  -------------------

file1 = open("sample.txt", "r")
count = len(file1.readlines())
print("Total number of lines in the file:", count)
file1.close()
Example : A Python program to remove or delete the contents of a file or directory.
import os
os.remove("sample.txt")
# os.unlink("sample.txt")
print("File removed successfully")

NB : Gives error if file does not exist.

-----------------------  OR  ----------------------

from pathlib import Path

file1 = Path("sample.txt")
file1.unlink()

NB: Modern and recommended method of file deletion.

-----------------------  OR  ----------------------

To Remove File with Check
import os
if os.path.exists("sample.txt"):
    os.remove("sample.txt")
    print("File deleted")
else:
    print("File not found")

-----------------------  OR  ----------------------

To Remove Multiple Files

import os
file1 = ["a.txt", "b.txt", "c.txt"]

for x in file1:
    if os.path.exists(x):
        os.remove(x)

-----------------------  OR  ----------------------

To Remove Only Empty Directory
import os
os.rmdir("New Folder1")
print("Empty Directory or Folder deleted")
           OR
from pathlib import Path
Path("NewFolder1").rmdir()

-----------------------  OR  ----------------------

To Remove mainly Non-Empty (but also empty)Directory
import shutil
shutil.rmtree("New Folder1")
print("Non- Empty Directory and its contents deleted")

NB : Deletes directory along with all files and subfolders.

-----------------------  OR  ----------------------

To Remove Non-Empty Directory safely and with check
import os
import shutil

if os.path.exists("New Folder1"):
    shutil.rmtree("New Folder1")
else:
    print("Directory not found")
Example : A Python program to edit or update the stored contents in a file.

NB: Python does not support in-place editing easily. Since files cannot be edited directly at a specific position easily, this is usually done by reading the existing content and then writing updated content back using appropriate file modes.

with open("sample.txt", "r") as file1:
    content = file1.read()

content1 = content.replace("Python", "Python Programming") # replaces Python with Python Programming.

with open("sample.txt", "w") as file1:
    file1.write(content1)

-----------------------  OR  ----------------------

with open("sample.txt", "a") as file1:
    file1.write("\nThis line is added to the end of the existing file without removing or overwriting the previous one.")

-----------------------  OR  ----------------------

TO UPDATE THE OONTENTS OF SPECIFIC LINES

with open("sample.txt", "r") as file1:
    lines = file1.readlines()
lines[1] = "This is updated second line\n"

with open("sample.txt", "w") as file1:
    file1.writelines(lines)

Loading

Categories: Python Theory

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.