我的代码遇到了一些问题,如果有人可以尝试提供帮助,我会很伤心。问题是(在 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()
如果有人可以在程序运行时帮助更新代码,我们将不胜感激。:)
想要编写的代码需要以wr
某种方式访问变量的值。您没有告诉我们该代码真正想要做什么,但作为起点,这里是修改示例的一种方法。
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(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
的一行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句