Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8832809
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T08:37:19+00:00 2026-06-14T08:37:19+00:00

def replace(): import tkinter.filedialog drawfilename = tkinter.filedialog.askopenfilename() list1= int(open(drawfilename,’w’)) del list1[-3:] input_list = input(Enter

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

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T08:37:20+00:00Added an answer on June 14, 2026 at 8:37 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given the code: import clr clr.AddReference('System') from System.Text.RegularExpressions import * def ReplaceBlank(st): return Regex.Replace(
import os def getName(AAPTLocation, apkFile): AAPTLocation = AAPTLocation.replace('\\','\\\\') apkFile = apkFile.replace('\\','\\\\') pname = ''
def citypop(): import csv F = open(Top5000Population.txt) csvF = csv.reader(F) D = {} with
I thought that I improve performance when I replace this code: def f(a, b):
Whats the easiest way in javascript to replace ABC, DEF, GHI with XYZ in
so i have the code : from Tkinter import * from urllib2 import *
I'm trying to replace two methods in calendar module: import calendar c = calendar.HTMLCalendar(calendar.MONDAY)
import json import urllib import re import binascii def asciirepl(match): s = match.group() return
I have created a function for decoding url. from urllib import unquote def unquote_u(source):
Here is my server.py : import BaseHTTPServer import SocketServer class TestRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): self.wfile.write(hello

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.