FILE JANDLING IN PYTHON

 CREATE  FILE IN D  DRIVE 

file = open("D:\\student.txt", "w")

file.write("Name: Rahul\n")

file.write("Course: Python Programming\n")

file.write("Marks: 85\n")

file.close()

print("File created successfully!")


OPEN  FILE  FROM D DRIVE 

with open("D:\\student.txt", "r") as file:
    data = file.read()

print("File Content:")
print(data)


FILE  EXIST  IN D DRIVE  HOW TO CHECK 

import os

file_path = "D:\\student1.txt"

if os.path.exists(file_path):
    print("File exists in D drive.")
else:
    print("File does not exist in D drive.")

FILE EXIST THEN CREATE NEW FILE 

import os

old_file = "D:\\student.txt"
new_file = "D:\\student_new.txt"

if os.path.isfile(old_file):
    print("Old file exists.")

    with open(new_file, "w") as file:
        file.write("This is a new file.\n")
        file.write("Created because student.txt already exists.")

    print("New file created successfully.")
else:
    print("Old file does not exist.")






Comments

Popular posts from this blog

Python none

python random module