您对如何使用文件感到非常困惑。
首先,你为什么要这样做int(open(filename, "w"))
?要打开文件进行写入,只需使用:
outfile = open(filename, "w")
然后文件不支持项目分配,所以这样做fileobject[key]
没有意义。另请注意,打开文件"w"
会删除以前的内容!所以如果你想修改文件的内容,你应该"r+"
使用"w"
. 然后,您必须读取文件并解析其内容。在您的情况下,最好先读取内容,然后创建一个新文件来写入新内容。
要将数字列表写入文件,请执行以下操作:
outfile.write(','.join(str(number) for number in list2))
str(number)
将整数“转换”为其字符串表示形式。使用逗号作为分隔符连接iterable','.join(iterable)
中的元素并将字符串写入文件。outfile.write(string)
此外,将导入放在函数之外(可能在文件的开头),每次使用模块时都不需要重复它。
完整的代码可以是:
import tkinter.filedialog
def replace():
drawfilename = tkinter.filedialog.askopenfilename()
# read the contents of the file
with open(drawfilename, "r") as infile:
numbers = [int(number) for number in infile.read().split(',')]
del numbers[-3:]
# with automatically closes the file after del numbers[-3:]
input_list = input("Enter three numbers separated by commas: ")
# you do not have to strip the spaces. int already ignores them
new_numbers = [int(num) for num in input_list.split(',')]
numbers = new_numbers + numbers
#drawfilename = tkinter.filedialog.askopenfilename() if you want to reask the path
# delete the old file and write the new content
with open(drawfilename, "w") as outfile:
outfile.write(','.join(str(number) for number in numbers))
更新:如果你想处理多个序列,你可以这样做:
import tkinter.filedialog
def replace():
drawfilename = tkinter.filedialog.askopenfilename()
with open(drawfilename, "r") as infile:
sequences = infile.read().split(None, 2)[:-1]
# split(None, 2) splits on any whitespace and splits at most 2 times
# which means that it returns a list of 3 elements:
# the two sequences and the remaining line not splitted.
# sequences = infile.read().split() if you want to "parse" all the line
input_sequences = []
for sequence in sequences:
numbers = [int(number) for number in sequence.split(',')]
del numbers[-3:]
input_list = input("Enter three numbers separated by commas: ")
input_sequences.append([int(num) for num in input_list.split(',')])
#drawfilename = tkinter.filedialog.askopenfilename() if you want to reask the path
with open(drawfilename, "w") as outfile:
out_sequences = []
for sequence, in_sequence in zip(sequences, input_sequences):
out_sequences.append(','.join(str(num) for num in (in_sequence + sequence)))
outfile.write(' '.join(out_sequences))
这应该适用于任意数量的序列。请注意,如果您在某处有额外的空间,您将得到错误的结果。如果可能的话,我会将这些序列放在不同的行上。