0

I am using Python 2.7 and am trying to get my program to check if a file exists and if it does, the program should then ask the user if they want to overwrite it. If the file is not there, a new one should be created. These two steps are repeated where the file is found to be existing. Here is the code:

import os.path
file_name = input("Please enter the name of the file to save your data       to: Example: test.txt ")
file_open = open(file_name, "w")
if os.path.isfile(file_name):
    print ("File exists")
    decide = input("Do you want to overwrite the file?, Yes or No")
    control = True
    while control:
        if decide != "Yes":
            file_name = input("Please enter the name of the file to save your data to: Example: test.txt ")
            if os.path.isfile(file_name):
                print ("File exists")
        else:
            newFile = open(file_name, "w")
            newFile.write(str(model))
            newFile.close()
            control=False
else:
    print("Creating a new file..................")
    file_open.write(str(model))
    file_open.close()
Psytho
  • 3,313
  • 2
  • 19
  • 27
Owen
  • 1
  • 4
  • 3
    possible duplicate of [Differences between \`input\` and \`raw\_input\`](http://stackoverflow.com/questions/3800846/differences-between-input-and-raw-input) – TigerhawkT3 Sep 24 '15 at 06:50
  • If I use a different name, python just highlights that particular name as causing the name error message – Owen Sep 24 '15 at 06:55
  • possible duplicate of [What's the difference between raw\_input() and input() in python3.x?](http://stackoverflow.com/questions/4915361/whats-the-difference-between-raw-input-and-input-in-python3-x) – hjpotter92 Sep 24 '15 at 06:56
  • Oooh thanks Tigerhawk, I had forgotten the versions problems!! Cheers its sorted now! – Owen Sep 24 '15 at 06:59
  • 1
    `if os.path.isfile(file_name):` - this line will always return `True` because you create a file with the name `file_name` right before the`if`-statement. So you will never reach `else` that is going to create a file. – Psytho Sep 24 '15 at 07:04

1 Answers1

0

In lines 2, 6 and 10 it should be raw_input() as you are reading string, and check indentation of code.

Psytho
  • 3,313
  • 2
  • 19
  • 27
Naveen.sn
  • 72
  • 6
  • I have sorted the input() problem but my idea is to check if the file exists and then create a new one with user inputting the name of the file. For as long as the file that the user types in is existing and they choose not to overwrite it, the program must keep asking them for a new file name – Owen Sep 24 '15 at 07:04
  • Your code will do same as expected if you give decide='No'. – Naveen.sn Sep 24 '15 at 09:52