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:
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:
str(number)“converts” an integer into its string representation.','.join(iterable)joins the elements in iterable using a comma as separator andoutfile.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:
Update:
If you want to deal with more than one sequence you can do this:
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.