使用循环写入 CSV 文件的 Python 代码
我是 Python 编码新手。我在将数据文件发送到 CSV 文件时遇到一些问题。我不确定为什么它没有按照打印的方式发送。我无法设法纠正循环方式。我在代码中错过了什么?
图 1:显示了如何以正确的方式打印换行符。但是,当我使用 for 循环时,它会发送如图 2 所示的文件。 我犯了什么错误以及如何解决发送与打印数据中显示的完全相同的问题?
图片:1
图片:2
图片:3
I am novice with Python coding. I am having some issue to send data file into CSV file. I am not sure why it's not being sent the way it's being printed. I couldn't manage to correct way looping. What did I miss in the code?
Image 1: shows how newline is being printed on right manner. However, when I use the for loop down it's sending the file like image 2.
What did I mistake and how to resolve to send exactly the same as showing into print data?
Image:1
Image:2
Image:3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每次在第 52 行循环遍历第一个 for 循环中的变量“newfile”时,它都会被覆盖。最后,当您退出循环并在第 72 行进入新循环时,您将迭代“ newfile' 变量(参见 https://stackoverflow.com/a/1816897/5198805)。您还多次打开同一个文件并覆盖它。您应该打开它一次,然后继续编写每一行。
您应该将值保存在临时列表中
the variable 'newfile' in your first for-loop keeps getting overwritten each time your loop through it at line 52. Finally when you exit the loop and enter a new loop at line 72, you are iterating over the LAST assignment set on the 'newfile' variable (see https://stackoverflow.com/a/1816897/5198805) . You're also opening the same file multiple times and ovewriting it. You should open it once and then keep writing each line.
You should save the values in a temporary list