title: I need to edit/overwrite a text file that holds a customers information using easygui and i need to select which customers information i am editing
body: <p>This is my python code you will need easy gui to run it and the username is q and the password is 1 i need to select a customer and then overwrite there information and not change the id number that it already has the code is from a different program i have wrote and the create despatch notes is the edit function or the not edit function i guess</p>
  <pre><code>   #Kit order database
  from easygui import *
  import csv
  from easygui import EgStore
  from datetime import *
  
  import os
  username = &quot;&quot;
  password = &quot;&quot;
  failed = 0
  
  #continue/cancel box to request authentication to start the program
  proceedLogon = ccbox(&quot;Authentication required to use this program&quot;,&quot;Security&quot;)
  
  #if cancel is selected on the continue/cancel box to start the program
  if proceedLogon == 0:
      exit()
  
  #while username or password are wrong and some of the 3 treis remain&quot;
  while (username != &quot;q&quot; or password != &quot;1&quot;) and failed &lt; 3:
      #set a list for field names to enter
      fieldNames = [&quot;Username&quot;,&quot;Password&quot;]
      #create a list of values input in multi password box
      fieldValues = multpasswordbox(&quot;Logon&quot;,&quot;System Access&quot;,fieldNames)
  
      #handle user using cancel button on multpasswordbox, setting username to an
      #empty string which will give a failed atte,pt
      if fieldValues == None:
          proceedLogon = ccbox(&quot;Are you sure you want to exit?&quot;,&quot;Logon&quot;)
  
          # if continue is selected on the continue/cancel box exit the program
          if proceedLogon == 1:
              exit()
      else:
          #assign username and password to values input by user
          username = fieldValues[0]
          password = fieldValues[1]
  
      #add one to the failed count if the username or password is wrong
      if (username != &quot;q&quot; or password != &quot;1&quot;):
          failed = failed+1
  
      #if fail count exhausted
      if failed == 3:
          #message box to state login has failed
          msgbox(&quot;Login failed&quot;)
          #exit the program
          exit()
      elif(username !=&quot;q&quot; or password !=&quot;1&quot;) and failed &lt; 3:
          #build a string for message box output to show number of tries remaining
          failedMessage = (str(3-failed)+&quot; tries remaining&quot;)
          msgbox(failedMessage, &quot;Failed Logon&quot;)
  
  #if username and password are corret start the program
  msgbox(&quot;Login successful&quot;)
  
  #function to add a record to a givern record
  def setUpFolders():
      #if the program does not see a Invoices folder it creates one
      if not os.path.exists(&quot;invoices&quot;):
          os.makedirs(&quot;invoices&quot;)
      #if the program does not see a despatch notes folder it creates one
      if not os.path.exists(&quot;despatch notes&quot;):
          os.makedirs(&quot;despatch notes&quot;)
      #if the program does not see a paid invoices folder it creates one
      if not os.path.exists(&quot;paid invoices&quot;):
          os.makedirs(&quot;paid invoices&quot;)
          
  def addRecord(values, filename):
  
      #set highest file number to 01
      highestFileID = 0
  
      #try opening file for reading, else use w+ to create file
      #and reading records from file to get the highest ID number from first record
      
      try:
          file = open(filename, &quot;r+&quot;)
  
          #for each line in the file
          for line in file:
              #create a blank list for each line of the file to be read into
              records = []
  
              #at each pipe character split the string 
              for field in line.split(&quot;|&quot;):
                  #add each entry in turn to a new position in the list
                  records.append(field)
  
              #if the number in the first postition in the
              #list is higher than the current highestfileID
              if int(records[0]) &gt; highestFileID:
                  #update the highestFileID to that higher
                  #number which is in the 1st positio of the list
                  highestFileID = int(records[0])
  
          file.close()
  
      #if file isn't there then create the file
      except EnvironmentError as exception:
          #create file for later appending
          file = open(filename,&quot;w+&quot;)
  
      #create primary key for record
      key = str(highestFileID + 1)
      #create string for record joining the key to the details sent to this function(member/kit item/order)
      record = &quot;|&quot;.join([key] + values)
  
      #write string to appropriate record file
      file = open(filename,&quot;a&quot;)
      file.write(record + &quot;\n&quot;)
      file.close()
  
      #returns next runner,event or entry ID
      return highestFileID + 1 
  
              
  def enterClubMember():
  
      #set fields for member information input dialogue box
      msg = &quot;Enter the new information&quot;
      title = &quot;Add a new member&quot;
      fieldNames = [&quot;Name&quot;,&quot;Street Address&quot;,&quot;Town/City&quot;,&quot;Postcode&quot;]
  
      #setting user details as a blank list
      fieldValues = []
  
      #set number of complete entries member details to 0
      numberOfEntries = 0
      #while there are less than 4 complete entries
      while numberOfEntries &lt; 4:
          #input field values(new member details) in a multenter box
          fieldValues = multenterbox(msg,title,fieldNames)
  
          #cancel button option for member details entry to return to the menu
          if fieldValues == None:
              mainMenu()
  
          #check each entry is the input list to see if it is not blank
          #adding one to the complete entry count as appropriate
          for entry in fieldValues:
                  if entry != &quot;&quot;:
                      numberOfEntries += 1
  
          #show error message if any of the lines was found to be blank 
          if numberOfEntries &lt; 4:
              msgbox(&quot;All fields must be filled in&quot;)
              #reset counter for complete entries ready for data re-entry
              numberOfEntries = 0
              
      
      #format member details for neat case
      fieldValues[0] = fieldValues[0].title()
      fieldValues[1] = fieldValues[1].title()
      fieldValues[2] = fieldValues[2].title()
      fieldValues[3] = fieldValues[3].upper()
  
      #return the list of entered member details to file by
      #calling the addRecord function sending parametres of
      #the member details list and the file name to save to
      addRecord(fieldValues,&quot;Bank company customers.txt&quot;)
  
  
  
      
  def recordList(fileName):
  
      #set record list empty
      records = []
      #attempt to open the requested filename
      try:
          file = open(fileName, &quot;r+&quot;)
  
          #process each line of the file
          for line in file:
              #create 2d list of contects from each line if the records file
              records.append(line.split(&quot;|&quot;))
  
          file.close()
      #if the file cannot be opened or loooped through
      except EnvironmentError as exception:
          msgbox(&quot;Could not open/read from the file&quot;)
          #would return nothing
          return None
  
      #return records to the calling function
      return records
  
  
  #creating a function and setting it to createDespatchNote()
  def createDespatchNote():
      msg = &quot;Enter the new information&quot;
      title = &quot;Add a new member&quot;
      fieldNames = [&quot;Name&quot;,&quot;Street Address&quot;,&quot;Town/City&quot;,&quot;Postcode&quot;]
  
      #calling a different function to find the text file 
      orderList = recordList(&quot;Bank company customers.txt&quot;)
      updatedlist=[]
      temporarylist=[]
      
      with open(&quot;Bank company customers.txt&quot;,newline=&quot;&quot;) as f:
        reader=list(csv.reader(f))#convert iterable to a list to make it easier 
        ynbox(&quot;CHANGE PASSWORD?!&quot;)
        username=enterbox(&quot;Enter the name for the required customer:&quot;)
        temporarylist=reader #store a copy of the data
        
        for row in reader: #for every row in the file
            for field in row:
                  if field==username: #if a field is == to the required username
                      updatedlist.append(row) #add each row, line by line, into a list called 'udpatedlist'
                      newpassword=multenterbox(msg,title,fieldNames)
                      updatedlist[1][2] = newpassword #set the field for password to the new password
                 
        
        updatepassword(updatedlist,temporarylist)
          
  def updatepassword(updatedlist,temporarylist):
      for index, row in enumerate(temporarylist):
          for field in row:
              if field==updatedlist[1]:
                  temporarylist[index]=updatedlist #replace old record with updated records
  
      
      with open(&quot;Bank company customers.txt&quot;,&quot;w&quot;,newline=&quot;&quot;) as f:
          Writer=csv.writer(f)
          Writer.writerows(temporarylist)
          print(&quot;File has been updated&quot;)
  
  
      
      
  
      
  
      
  def markInvoiceAsPaid():
  
      #calling a different function to find the text file
      orderList = recordList(&quot;Bank Members.txt&quot;)
      #if their isnt a file ouput error
      if orderList == None:
          msgbox(&quot;Error reading order file&quot;)
          return
  
      #setting choicelist to an empty list
      choiceList = []
  
      #for every order in the text file run the following code
      for order in orderList:
          #setting choice to a blank string
          choice = &quot;&quot;
          #for every position in the order
          for field in order:
  
              #after each field add a double space
              choice += &quot;{}|&quot;.format(field)
          #after the choice list add the users choice to the end of the list 
          choiceList.append(choice)
  
      #creating a title and message to go in a choice box
      title = &quot;Mark order as paid&quot;
      msg = &quot;Select order to mark as paid&quot;
      #creating a choice box to mark the order as paid 
      orderChoice = choicebox(msg,title,choiceList)
  
      #if their is no orders in the choice return to the main menu
      if orderChoice == None:
          mainMenu()
  
      #setting markAsPaidID as order choice split with double space at position 0 with a strip
      markAsPaidID = orderChoice.split(&quot;  &quot;)[0].strip()
  
      #setting invoiceFile as the invoices text file
      invoiceFile = &quot;invoices/order {} - confirmation.txt&quot;.format(markAsPaidID)
  
      #if their is not an invoice file follow the following code
      if os.path.isfile(invoiceFile):
          #rename a text file called paid invoices and mark it as paid
          os.rename(invoiceFile,&quot;paid invoices/Order {} - paid.txt&quot;.format(markAsPaidID))
          #creating a message to be used in a text box
          msg = &quot;Order &quot; + markAsPaidID + &quot; has been marked as paid&quot;
          #telling the user that the order has been marked as paid
          msgbox(msg,&quot;Confirmation&quot;)
          return
      #if the order does not successfully get marked as paid output an error
      else:
          msg = &quot;failed to mark invoice as paid, because the original invoice could not be found&quot;
          msgbox(msg,&quot;Failed operation&quot;)
  
  #creating a function for unpaid invoices
  def checkForUnpaidInvoices():
  
      #setting unpaid invoices as an empty list
      unpaidInvoices = []
  
      #for every file in invoices 
      for filename in os.listdir(&quot;invoices&quot;):
  
          #try the following code
          try:
              #checking the date on the text file name 
              modifiedTime = os.path.getmtime(&quot;invoices/&quot; + filename)
          #if their is no time in the file name then it will outpun an error
          except OSError:
              modifiedTime = 0
              msgbox(&quot;Unable to find files to check dates&quot;,&quot;Error&quot;)
              
          #setting modified date 
          modifiedDate = datetime.fromtimestamp(modifiedTime)
  
          #if modified date is more than 7 add it to the unpaid invoices file
          if modifiedDate + timedelta(days=7) &lt; datetime.now():
              unpaidInvoices.append(filename)
  
      #if the unpaid invoices file is larger than 0 run the following code
      if len(unpaidInvoices) &gt; 0:
          #output the unpaid invoices
          msgbox(&quot;\n&quot;.join(unpaidInvoices),&quot;Unpaid invoices&quot;)
      #if their are no unpaid invoices outputing saying that their are no unpaid invoices
      else:
          msgbox(&quot;There are not unpaid receipts over 7 days old&quot;,&quot;Report&quot;)
      
  def mainMenu():
  
      #initialise choice to an option that is not available
      choice = 5
  
      #while choice isnt the exit option
      while choice != 0:
          #set the button names as a list
          choices = [&quot;Exit&quot;,&quot;New club member&quot;,
                     &quot;New kit item&quot;,&quot;New kit order &amp; receipt&quot;,&quot;Create despatch note&quot;,
                     &quot;Mark invoice as paid&quot;,&quot;check for unpaid orders over 7 days old&quot;]
  
          #input users gui choice
          choice = indexbox(&quot;Choose a menu option&quot;,&quot;Kit Orders Database&quot;,
                            choices)
  
          #if the choice to exit is selected then exit with a message
          if choice == 0:
              msgbox(&quot;Good bye!&quot;)
              exit()
          #else if choice is 1 call the enter club member function
          elif choice == 1:
              enterClubMember()
          #else if choice is 2 call the enter kit item function
          elif choice == 2:
              enterKitItem()
          #else if choice is 3 call the enter kit order function
          elif choice == 3:
              enterKitOrder()
          #else if choice is 4 call the create despatch note function
          elif choice == 4:
              createDespatchNote()
          #else if choice is 5 call the mark invoice as paid  function
          elif choice == 5:
              markInvoiceAsPaid()
          #else if choice is 6 call the check for unpaid invoices  function
          elif choice == 6:
              checkForUnpaidInvoices()
  
          #option for user using red cross exit button output invalid option
          elif choice == None:
              msgbox(&quot;Use the \&quot;Exit\&quot; option to leave the program&quot;,&quot;Invalid option&quot;)
  
  #calling the main menu function
  mainMenu()
  </code></pre>