我提示用户保存文件,我想自动保存文件。例如,假设用户将文本文件保存在名为" foo.txt"的程序下,我想自动创建一个名为" lengthfoo.txt"的文本文件。单词"长度"之前" foo"和" .txt"在" foo"之后。另一个例子:当用户保存" HelloWorld.txt"时,我希望程序自动保存另一个名为" lengthHelloWorld.txt"
的文件from ast import literal_eval
from Tkinter import *
from tkFileDialog import *
def loadFile():
try:
save_file = askopenfile(mode='r', defaultextension=".zw")
lengths_file = open("length%s.zw" % "origsavefilename", "r")
with save_file as f:
for line in f:
rectList.extend(literal_eval(line.strip()))
save_file.close()
lengths_file.close()
print "File Loaded"
def saveFile():
try:
save_file = asksaveasfile(mode='w', defaultextension=".zw")
if save_file is not None:
# Write the file to disk
lengths_file = open("length%s.zw" % "origsavefilename", "w")
save_file.close()
print "File Saved Successfully."
答案 0 :(得分:0)
请勿使用asksaveasfile
,而是使用asksaveasfilename
,它会返回所选的文件名而不是已打开的文件。
然后,您可以使用
等内容length
创建文件名
import os
save_filename = asksaveasfilename()
save_filename_split = os.path.split(save_filename)
save_filename_length = os.path.join(save_filename_split[0],
'length'+save_filename_split[-1])
然后你有两个文件名,你可以打开并写东西。