【问题标题】:Issues printing to a CSV in Python在 Python 中打印到 CSV 的问题
【发布时间】:2023-03-22 21:30:01
【问题描述】:

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

【问题讨论】:

  • thewriter.writerow 必须在您的 with open(...) as f 上下文中,缩进到同一级别。此外,在使用上下文管理器时,您不需要显式关闭文件句柄f
  • 好的有道理,谢谢
  • 帖子更新了,可以看看吗?
  • 请在您的错误中包含回溯,至少显示在您自己的代码中触发错误的位置。
  • 现在添加,抱歉我是新来的堆栈溢出所以不知道所有的约定

标签: python csv writetofile


【解决方案1】:

在写入文件之前您正在关闭文件:

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

【讨论】:

  • 我不敢相信我犯了一个愚蠢的错误。所以我纠正了这一点,但现在它实际上并没有在 csv 中写任何东西,它只是打印出“激活码等”而不是变量 im传递进去。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 2019-07-31
  • 2019-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多