Write a program that checks to see if the file name exists, it will give you an error message, if not, it will create the file.

 

Answer:

import os

if os.path.isfile('sample.txt'):

print ("You are trying to create a file that already exist!")

else:

f = open("sample.txt",'w')

Question 8-Write a program - Teachoo.JPG

Remove Ads

Transcript

Question 8 Write a program that checks to see if the file name exists, it will give you an error message, if not, it will create the file. Imports the ‘os module’ Checks if the file already exists Prints error message if the file already exists If the file doesn’t exist, creates a new file Output

Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.