【发布时间】:2018-03-21 02:06:58
【问题描述】:
我编写了这段代码来将标题写入 csv 文件:
with open(os.path.join(directory, 'UserPass.csv'), 'wb') as csvFile:
writer = csv.DictWriter(csvFile, fieldnames = ['Username', 'Password'], delimeter = ',')
writer.writeheader()
但是,它会出现一个错误,指出未定义目录。 为什么会发生这种情况,我将目录定义为什么? 有没有更好的方法来编写标题? 谢谢。
【问题讨论】:
-
错误告诉你在尝试使用之前没有给
directory变量赋值。 -
delimeter拼写错误,但逗号是默认值。 -
with open('UserPass.csv', 'w', newline='') as csvFile:将打开当前目录中的文件(因为您没有定义一个),并且newline=''是正确使用 Python 3.x 的csv模块所必需的。
标签: python python-3.x csv csv-write-stream