1

This is my code, If the file name exists it will ask the user if they would like to overwrite or not if they do not the code is sorted but I am struggling to find where it allow me overwrite to the excel file that is already in existance.

import os
filename = str(input("Please enter a file name\n"))
print(TableModel)
file_exists = False
while file_exists == False:
    if os.path.isfile(filename):
        file_exists = True
        overwrite = str(input("File name is in existance. Would you like to overwrite this yes. Y for yes, N for no\n"))

        if overwrite == "N" or overwrite == "n":
            print ("You have chosen not to overwrite this file")
            filename = str(input("Please enter a different file name\n"))

        elif overwrite == "y" or overwrite == "y":
            file_exists = True
            f = open(filename, 'w')
            text = f.read()
            text = re.sub('foobar', 'bar', text)
            f.seek(0)
            f.write(text)
            f.truncate()
            f.close()
Jakeolan
  • 11
  • 1
  • 3
  • You should look into the openpyxl library. Normal file methods will not work for excel – Mark Skelton Mar 22 '16 at 19:44
  • When i save it i Save it as exc – Jakeolan Mar 22 '16 at 19:46
  • It is not very clear your question: from the code it seems that you are opening a normal text file and not an excel file. If it is just a plain text file, opening the file with `open(filename, 'w')` overwrites the existing file. For opening an actual excel file and correctly interpreting it, you should use some packages, like `pandas` or `xlrd`. Note also that the `if` block in which you don't want to overwrite the file, you are not actually creating a new file. I'm not sure whether in the following code not listed in the question, you are actually creating a new file. – albertoql Mar 22 '16 at 19:48
  • This is only a snippet – Jakeolan Mar 23 '16 at 17:55

1 Answers1

0

If the user chooses to overwrite the file, the set of seek, write, truncate seeks to the beginning of the file, writes out the new one, and then truncates (removes) any remnants of the original file.

Further, performing these operations by calling with to get your filehandler is much safer.

with open(filename, 'r+') as fh:
    text = fh.read()                      # read file
    text = re.sub('foobar', 'bar', text)  # perform operation
    fh.seek(0)                            # seek the to beginning
    fh.write(text)                        # write out new contents
    fh.truncate()                         # truncate any leftovers
ti7
  • 16,375
  • 6
  • 40
  • 68