def replace():
import tkinter.filedialog
drawfilename = tkinter.filedialog.askopenfilename()
list1= int(open(drawfilename,'w'))
del list1[-3:]
input_list = input("Enter three numbers separated by commas: ")
list2 = input_list.split(',')
list2 = [int(x.strip())for x in list2]
list1[0:0] = list2
list1.write(list1)
list1.close()
import tkinter.filedialog
drawfilename = tkinter.filedialog.askopenfilename()
list1= open(drawfilename,'r')
line = list1.readlines()
list1.close()
我想打开一个包含1,2,3,4,5,6,7,8,9
的.txt
文件,删除最后三个值,然后要求用户输入三个数字并将它们添加到列表的开头(示例输入12,13,14
给出12,13,14, 1,2,3,4,5,6
)。然后我想用这个新列表覆盖原来的列表。当用户再次打开例程时,我希望list1成为新的list1。
在stackflow的帮助下,我得到了新的list1,但是在打开和重写文本文件时遇到了困难。未声明全局列表1的错误将停止例程的进程。在
你真的很困惑如何使用一个文件。在
首先,你为什么要做
int(open(filename, "w"))
? 要打开要写入的文件,只需使用:则文件不支持项分配,因此}。
然后必须读取文件并分析其内容。在您的情况下,最好先读取内容,然后创建一个新文件来写入新内容。在
fileobject[key]
没有意义。还要注意,用"w"
打开一个文件会删除先前的内容!因此,如果要修改文件的内容,应该使用"r+"
而不是{要将数字列表写入文件,请执行以下操作:
^{2}$str(number)
将整数“转换”为其字符串表示形式。','.join(iterable)
使用逗号作为分隔符连接iterable中的元素,outfile.write(string)
将字符串写入文件。在另外,将导入放在函数之外(可能在文件的开头),并且不需要每次使用模块时都重复导入。在
完整的代码可以是:
更新: 如果要处理多个序列,可以执行以下操作:
这应该适用于任意数量的序列。请注意,如果你有一个额外的空间,你会得到错误的结果。如果可能的话,我会把这些序列放在不同的行上。在
相关问题 更多 >
编程相关推荐