Для работы я создал очень простой пользовательский интерфейс, который при нажатии btn
генерирует пользователей с помощью веб-службы.Я хочу быть в состоянии записать эти данные пользователя в CSV, но я изо всех сил.Может ли кто-нибудь помочь, пожалуйста?
Я прокомментировал в своем коде, где возникает проблема
#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()
РАЗЛИЧНЫЕ ФАЙЛЫ 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
Я получаю ошибку:
'Неопределенная переменная' TheWriter 'thewriter.writerow ([код активации, mobile_scope_token, идентификатор устройства, идентификатор пользователя, идентификатор ввода]]
Существует дваразные методы / модули, основной и метод записи в файл, я думаю, проблема в том, что я не импортирую что-то правильно, но я действительно не уверен.Может кто-нибудь, пожалуйста, помогите
Исправлена эта ошибка, но есть еще одна сейчас.«Операция ввода-вывода для закрытого файла»
'''
Created on 14 Sep 2018
@author: amcfb
'''
import requests
#Needs the following files
import generate_activation_code
import create_group
import write_to_file
import add_user_to_group
import retrieve_group_properties
import get_mobile_scope_token
import register_user_to_suitcase
import create_bearer_token
def generateUser(amountOfUsers, inputGroupId):
#A loop which will iterate as many times as selected by user
for x in range(int(amountOfUsers)):
print('\n ********* CREATING USER ' + str(x + 1) + ' ********* \n')
arity_client_id = 'uJdjKVrdpJyR5kJNFzwF1cfLCvWA4YGA'
arity_client_secret = 'eHQENQpgXMlc17fe'
#create bearerToken
access_token, proxies = create_bearer_token.createBearerToken(requests)
#Register user to suitcase
proxies, bearerToken, userId, deviceId = register_user_to_suitcase.registerUserToSuitcase(requests, access_token, proxies)
#Get the mobile scope token
mobile_scope_token = get_mobile_scope_token.getMobileScopeToken(arity_client_id, arity_client_secret, userId, deviceId, proxies, requests)
#Generate activation code
activation_code = generate_activation_code.generateActivationCode(userId, mobile_scope_token, deviceId, bearerToken, requests, proxies)
#Create group
create_group.createGroup(inputGroupId, bearerToken, requests, proxies)
#Add user to group
add_user_to_group.addUserToGroup(inputGroupId, userId, bearerToken, requests, proxies)
#Retrieve group properties
retrieve_group_properties.retrieveGroupProperties(inputGroupId, bearerToken, requests, proxies, activation_code, mobile_scope_token, deviceId, userId)
#Write to file
write_to_file.writeToFile(activation_code, mobile_scope_token, deviceId, userId, inputGroupId)
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
#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'])
#Change name of file to current date and Time
#Get amountOfUsers to work
#See if i need the second for loop below
#Open file 'MyCsv' to write to, called f
#with open('mycsv.csv', 'w', newline='') as f:
#thewriter.writeroßw(['Activation Code', 'Mobile Scope Token','DeviceId','UserId ','GroupID'])
#f.close()
Trackback :::
traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 1702, in __call__
return self.func(*args)
File "/Users/mcur4/user-creator/src/main.py", line 49, in clicked
user_creation.generateUser(amountOfUsers, inputGroupId)
File "/Users/mcur4/user-creator/src/user_creation.py", line 51, in generateUser
write_to_file.writeToFile(activation_code, mobile_scope_token, deviceId, userId, inputGroupId)
File "/Users/mcur4/user-creator/src/write_to_file.py", line 25, in writeToFile
thewriter.writerow(['Activation Code', 'Mobile Scope Token','DeviceId','UserId ','GroupID'])
ValueError: I/O operation on closed file.