33

I would like to know how I could check to see if a file exist based on user input and if it does not, then i would like to create one.

so I would have something like:

file_name = input('what is the file name? ')

then I would like to check to see if file name exist.

If file name does exist, open file to write or read, if file name does not exist, create the file based on user input.

I know the very basic about files but not how to use user input to check or create a file.

krona
  • 625
  • 3
  • 9
  • 13

2 Answers2

52

if the file is not a file :(return False)

import os.path
if not os.path.isFile(file_name):
      print("The File s% it's not created "%file_name)
      os.touch(file_name)
      print("The file s% has been Created ..."%file_name)

And you can write a simple code based on (try,Except):

try:
    my_file = open(file_name)
except IOError:
    os.touch(file_name)
rofrol
  • 14,438
  • 7
  • 79
  • 77
saudi_Dev
  • 829
  • 2
  • 7
  • 11
5

To do exactly what you asked:

You're going to want to look at the os.path.isfile() function, and then the open() function (passing your variable as the argument).


However, as noted by @LukasGraf, this is generally considered less than ideal because it introduces a race condition if something else were you create the file in the time between when you check to see if it exists and when you go to open it.

Instead, the usual preferred method is to just try and open it, and catch the exception that's generated if you can't:

try:
    my_file = open(file_name)
except IOError:
    # file couldn't be opened, perhaps you need to create it
Amber
  • 507,862
  • 82
  • 626
  • 550
  • Hmm, what if the user enters the name of a directory? Wouldn't `.exists()` return `True`, but opening would then fail? – Tim Pietzcker May 04 '14 at 17:15
  • @TimPietzcker Good call; updated to `isfile()`. – Amber May 04 '14 at 17:16
  • 2
    That's exactly what you should **not** do, because that introduces a [race condition](http://stackoverflow.com/questions/14574518/how-does-using-the-try-statement-avoid-a-race-condition). – Lukas Graf May 04 '14 at 17:17
  • @LukasGraf *sigh* we're going down this again. Fine, I'll write up an entire explanation of exceptions as well for a user that is still figuring out how to use user input. Stand by... – Amber May 04 '14 at 17:18
  • @Amber no, just mark it as a duplicate, since this has been answered over and over again. – Lukas Graf May 04 '14 at 17:19