简体   繁体   English

如何在Python中覆盖Excel文件

[英]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. 这是我的代码,如果文件名存在,它将询问用户是否要覆盖,如果他们不对代码进行排序,但我正在努力寻找它可以覆盖我已经在其中的excel文件的位置存在。

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. 如果用户选择覆盖文件,设定的seekwritetruncate 搜索到文件的开头, 出去了新的一个,然后截断 (删除)的原始文件的任何残余。

Further, performing these operations by calling with to get your filehandler is much safer. 此外,通过调用来获取文件with来执行这些操作要安全得多。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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