更新程序以在python中制作CSV文件

我的代码遇到了一些麻烦,如果有人可以尝试和提供帮助,我会很痛苦。问题是(在python上),是当用户输入要创建的csv文件的名称时。CSV文件仅在程序完成后显示。但是,我想在 csv 中放入一些东西,因为它还没有被创建,我不能。这是我的代码...


import csv

def start():

   NewCSV = input('Name of csv: ')


   with open(NewCSV + '.csv', 'w') as myfile:

      wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)


      Code_that_writes_in_CSV()


def Code_that_writes_in_CSV():

   print('') #Cant write this code because the file isn't created until the programme finishes

start()

如果有人可以在程序运行时帮助更新代码,我们将不胜感激。:)


慕标琳琳
浏览 127回答 1
1回答

当年话下

想要编写的代码需要以wr某种方式访问变量的值。您没有告诉我们该代码真正想要做什么,但作为起点,这里是修改示例的一种方法。import csvdef start():    NewCSV = input('Name of csv: ')    with open(NewCSV + '.csv', 'w') as myfile:        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)        Code_that_writes_in_CSV(wr)def Code_that_writes_in_CSV(handle):    handle.writerow([''])更常见的安排是将所有 CSV 处理保留在单个函数中,并且可能在单独的函数中执行一些计算。def write_to_csv(filename):    with open(filename, 'w') as myfile:        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)        for row in code_that_calculates_a_row_at_a_time():                wr.writerow(row)一次计算一行的代码可以是行return的列表,或者一次可以是yield一行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python