简体   繁体   中英

Python writing and reading a txt file

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

I want to open a .txt file containing 1,2,3,4,5,6,7,8,9 , remove the last three values then ask a user to input three numbers and add them to the beginning of the list ( example input 12,13,14 gives 12,13,14, 1,2,3,4,5,6 ). Then I want to overwrite the original list with this new list. When a user opens the routine again, I want list1 to be the new list1. With the help of stackflow I get the new list1, but am having difficulty opening and rewriting to the text file. The error that global list1 has not been declared stops the routine from progressing.

You are really confused on how to use a file.

First of all, why are you doing int(open(filename, "w")) ? To open a file for writing just use:

outfile = open(filename, "w")

Then files does not support item assignment, so doing fileobject[key] does not make sense. Also note that opening a file with "w" deletes the previous contents! So if you want to modify the contents of a file you should use "r+" instead of "w" . You then have to read the file and parse its contents. In your case is probably better to first read the contents and then create a new file to write the new contents.

To write a list of numbers to a file do:

outfile.write(','.join(str(number) for number in list2))

str(number) "converts" an integer into its string representation. ','.join(iterable) joins the elements in iterable using a comma as separator and outfile.write(string) writes string to the file.

Also, put the import outside the function(at the beginning of the file possibly) and you do not need to repeat it everytime you use the module.

A complete code could be:

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

Update: If you want to deal with more than one sequence you can do this:

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

This should work with any number of sequences. Note that if you have an extra space somewhere you'll get wrong results. If possible I'd put these sequences on different lines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM