0
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()

我想打开一个.txt包含 的文件1,2,3,4,5,6,7,8,9,删除最后三个值,然后要求用户输入三个数字并将它们添加到列表的开头(示例输入12,13,14给出12,13,14, 1,2,3,4,5,6)。然后我想用这个新列表覆盖原始列表。当用户再次打开例程时,我希望 list1 成为新的 list1。在 stackflow 的帮助下,我得到了新的 list1,但在打开和重写文本文件时遇到了困难。未声明 global list1 的错误会停止例程的进行。

4

1 回答 1

1

您对如何使用文件感到非常困惑。

首先,你为什么要这样做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)) 

这应该适用于任意数量的序列。请注意,如果您在某处有额外的空间,您将得到错误的结果。如果可能的话,我会将这些序列放在不同的行上。

于 2012-11-15T08:46:10.980 回答