Python编写和读取txt文件

时间:2012-11-15 08:39:40

标签: 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()

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

1 个答案:

答案 0 :(得分: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)将一个整数“转换”为其字符串表示形式。 ','.join(iterable)使用逗号作为分隔符加入 iterable 中的元素,outfile.write(string) 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)) 

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