Python编写和读取txt-fi

2024-10-01 11:30:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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的错误将停止例程的进程。在


Tags: 用户import列表closeinputtkinteropen例程
1条回答
网友
1楼 · 发布于 2024-10-01 11:30:55

你真的很困惑如何使用一个文件。在

首先,你为什么要做int(open(filename, "w"))? 要打开要写入的文件,只需使用:

outfile = open(filename, "w")

则文件不支持项分配,因此fileobject[key]没有意义。还要注意,用"w"打开一个文件会删除先前的内容!因此,如果要修改文件的内容,应该使用"r+"而不是{}。 然后必须读取文件并分析其内容。在您的情况下,最好先读取内容,然后创建一个新文件来写入新内容。在

要将数字列表写入文件,请执行以下操作:

^{2}$

str(number)将整数“转换”为其字符串表示形式。','.join(iterable)使用逗号作为分隔符连接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)) 

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

相关问题 更多 >