-3

For work I've made a very very basic UI that when a btn is clicked, it generates users using a web service. I want to be able to write these user details into a csv, but I'm struggling. Could someone please help?

I've commented in my code where the issue is occurring

#Needs to import user_creation to call and write_to_file to close file
import user_creation 
import write_to_file
from tkinter import *
from tkinter.ttk import *
import csv

#commented these lines out and added into clicked() within the GUI
#amountOfUsers = input("How many users would you like to create? ")
#inputGroupId = input("What group do you want to add this/these user/s to? ")
#Call generateUser in user_creation to generate the codes, it will then call write_to_file 
#user_creation.generateUser(amountOfUsers, inputGroupId)


window = Tk()
 
window.title("RR Testing Tool") #title of window
window.configure(background="gray85") #background colour
 
window.geometry('500x150') #size of window

#text label beside group name textbox
group_name_lbl = Label(window, text="Enter a Group Name")
group_name_lbl.grid(column=0, row=0)
group_name_lbl.configure(background="gray85")
 
#group name text box
txtbox = Entry(window,width=20)
txtbox.grid(column=1, row=0)

#text label beside combo box
num_of_users_lbl = Label(window, text="Select the Number of Users to Create")
num_of_users_lbl.grid(column=0, row=4)
 
#combo box with predefined values for number of users 1-15
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15)
combo.current(0) #set the selected item
combo.grid(column=1, row=4)

#this is called when the button is clicked
def clicked():
 
    inputGroupId = txtbox.get()
    
    #combo_value = combo.get()
    amountOfUsers = combo.get()
    
    #User the date and time from Write to File to name the file i am opening
    with open('date_time_filename_string', 'w', newline='') as f:
        thewriter = csv.writer(f)
    #Write the title of the csv before you start filling the body
    thewriter.writerow(['Activation Code', 'Mobile Scope Token','DeviceId','UserId ','GroupID'])   
    
    user_creation.generateUser(amountOfUsers, inputGroupId)    
    
    f.close()
    #group_name_lbl.configure(text= inputGroupId)

#button
submit_btn = Button(window, text="Create!!", command=clicked)
submit_btn.grid(column=1, row=10)


window.mainloop()

DIFFERENT FILES XXXXX

import datetime
import csv
from main import *

currentDate = datetime.datetime.now()

date_time_filename_string = currentDate.strftime("%Y-%m-%d-%H%M%S") + ".csv"

#f = open(date_time_filename_string,"w+")

    #Write to file - will be updated to CSV
def writeToFile(activation_code, mobile_scope_token, deviceId, userId, inputGroupId):
    #f.write('Activation Code = ' + activation_code + '\n')
    #f.write('Mobile Scope Token = ' + mobile_scope_token + '\n')
    #f.write('DeviceId = ' + deviceId + '\n')
    #f.write('UserId = ' + userId + '\n')
    #f.write('GroupId = ' + inputGroupId + '\n') 
    #f.write('\n')
    #Populate Body of CSV
    

The error I'm getting is:

'Undefined Variable 'TheWriter' thewriter.writerow(['activation_code', 'mobile_scope_token', 'deviceId', 'userId','inputGroupId'])

There are two different methods/modules, a main and a write to file method, I think the issue is that I'm not importing something correctly, but I'm really not sure. Could someone please help

tripleee
  • 175,061
  • 34
  • 275
  • 318
MurrackCarn
  • 21
  • 1
  • 7
  • `thewriter.writerow` must be inside your `with open(...) as f` context, indent it to the same level. Also, when using the context manager, you don't need to close the file handle `f` explicitly. – Christian König Sep 28 '18 at 14:07
  • Okay makes sense, thank you – MurrackCarn Sep 28 '18 at 14:29
  • Post updated, could you have a look? – MurrackCarn Sep 28 '18 at 14:50
  • Please include the traceback with your errors, at least showing where *in your own code* the error was triggered. – MisterMiyagi Sep 28 '18 at 14:52
  • 1
    Added now, sorry im new to stack overflow so dont know all the conventions – MurrackCarn Sep 28 '18 at 14:54
  • Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/)). By SE policy, any vandalism will be reverted. – tripleee Jul 27 '22 at 11:10
  • Separately, please only ask one question per post. If you have a new problem, post a new question (perhaps with a link to this one). – tripleee Jul 27 '22 at 11:11

1 Answers1

0

You are closing your file before writing to it:

with open('date_time_filename_string', 'w', newline='') as f:
    thewriter = csv.writer(f)  # !!! file is closed after this line
#Write the title of the csv before you start filling the body
thewriter.writerow(['Activation Code', 'Mobile Scope Token','DeviceId','UserId ','GroupID'])  

Using a with statement for a file closes it at the end of the block. That means thewriter has only a closed file to write to after the block.

Make sure that all lines that trigger a write to f are part of the with block:

with open('date_time_filename_string', 'w', newline='') as f:
    thewriter = csv.writer(f)
    #Write the title of the csv before you start filling the body
    thewriter.writerow(['Activation Code', 'Mobile Scope Token','DeviceId','UserId ','GroupID'])  
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • I cant believe i made a mistake that stupid.. So ive corrected that but now it isnt actually writing anything in the csv, its just printing out "Activation code, etc etc" instead of the variables im passing into it. – MurrackCarn Sep 28 '18 at 15:09