Python 中的 CSV 打印问题
Issues printing to a CSV in Python
为了工作,我做了一个非常非常基本的 UI,当单击 btn
时,它会使用 Web 服务生成用户。我希望能够将这些用户详细信息写入 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
我得到的错误是:
'Undefined Variable 'TheWriter'
thewriter.writerow(['activation_code', 'mobile_scope_token', 'deviceId', 'userId','inputGroupId'])
有两种不同的 methods/modules,一种是主要方法,另一种是写入文件方法,我认为问题是我没有正确导入某些东西,但我真的不确定。
有人可以帮忙
修正了这个错误,但现在还有一个。 "I/O Operation on closed file"
'''
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()
引用通告:::
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.
您将在写入文件之前关闭文件:
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'])
对文件使用 with
语句 在块的末尾关闭 它。这意味着 thewriter
在块之后只有一个关闭的文件要写入。
确保触发写入 f
的所有行都是 with
块的一部分:
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'])
为了工作,我做了一个非常非常基本的 UI,当单击 btn
时,它会使用 Web 服务生成用户。我希望能够将这些用户详细信息写入 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
我得到的错误是:
'Undefined Variable 'TheWriter' thewriter.writerow(['activation_code', 'mobile_scope_token', 'deviceId', 'userId','inputGroupId'])
有两种不同的 methods/modules,一种是主要方法,另一种是写入文件方法,我认为问题是我没有正确导入某些东西,但我真的不确定。 有人可以帮忙
修正了这个错误,但现在还有一个。 "I/O Operation on closed file"
'''
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()
引用通告:::
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.
您将在写入文件之前关闭文件:
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'])
对文件使用 with
语句 在块的末尾关闭 它。这意味着 thewriter
在块之后只有一个关闭的文件要写入。
确保触发写入 f
的所有行都是 with
块的一部分:
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'])