pythoncsvwritetofile

Issues printing to a CSV in Python


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


Solution

  • 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'])