在Python中将问题打印到CSV

时间:2018-09-28 14:01:56

标签: python csv writetofile

对于工作,我制作了一个非常基本的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

我得到的错误是:

  

'未定义变量'TheWriter'           thewriter.writerow([['activation_code','mobile_scope_token','deviceId','userId','inputGroupId'])

有两个不同的方法/模块,一个主要方法和一个写文件方法,我认为问题是我没有正确地导入某些东西,但是我不确定。 有人可以帮忙

解决了该错误,但现在又有一个错误。 “对已关闭文件的I / O操作”

'''
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.

1 个答案:

答案 0 :(得分:0)

您正在关闭文件,然后再写入文件:

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