简体   繁体   中英

How to overwrite an excel file in Python

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

If the user chooses to overwrite the file, the set of seek , write , truncate seeks to the beginning of the file, write s 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM