如何用Python覆盖excel文件

时间:2016-03-22 19:34:35

标签: python excel file overwrite

这是我的代码,如果文件名存在,它将询问用户是否要覆盖,如果他们没有对代码进行排序,但我很难找到它允许我覆盖到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()

1 个答案:

答案 0 :(得分:0)

如果用户选择覆盖该文件,则seekwritetruncate 设置到文件的开头出新的,然后截断(删除)原始文件的任何残余。

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