简体   繁体   English

如何将标题写入csv文件?

[英]How to write headers to a csv file?

I've wrote this code to write headers to a csv file:我写了这段代码来将标题写入 csv 文件:

    with open(os.path.join(directory, 'UserPass.csv'), 'wb') as csvFile:
    writer = csv.DictWriter(csvFile, fieldnames = ['Username', 'Password'], delimeter = ',')
    writer.writeheader()

However, it comes up with an error saying that directory is not defined.但是,它出现了一个错误,指出未定义目录。 Why is this happening, what would I define directory as?为什么会发生这种情况,我将目录定义为什么? Is there a better way to write headers?有没有更好的方法来写标题? Thank you.谢谢你。

Directory is the location of the directory (aka folder) that you want to save UserPass.csv. Directory 是您要保存 UserPass.csv 的目录(又名文件夹)的位置。 See os.path.join docs for more info.有关更多信息,请参阅os.path.join 文档

最简单的方法是使用sed因为您提到了替代方案,就这样做,

sed -i '1iUsername,Password' UserPass.csv

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM