Check sibling questions

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')


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

  1. Computer Science - Class 12
  2. Chapter 2 - File Handling in Python

About the Author

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo