[英]How to overwrite an excel file in Python
这是我的代码,如果文件名存在,它将询问用户是否要覆盖,如果他们不对代码进行排序,但我正在努力寻找它可以覆盖我已经在其中的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()
如果用户选择覆盖文件,设定的seek
, write
, truncate
搜索到文件的开头, 写出去了新的一个,然后截断 (删除)的原始文件的任何残余。
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.