使用循环写入 CSV 文件的 Python 代码

发布于 2025-01-11 10:04:04 字数 640 浏览 0 评论 0原文

我是 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

enter image description here

Image:2

enter image description here

Image:3

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九公里浅绿 2025-01-18 10:04:04

每次在第 52 行循环遍历第一个 for 循环中的变量“newfile”时,它都会被覆盖。最后,当您退出循环并在第 72 行进入新循环时,您将迭代“ newfile' 变量(参见 https://stackoverflow.com/a/1816897/5198805)。您还多次打开同一个文件并覆盖它。您应该打开它一次,然后继续编写每一行。

您应该将值保存在临时列表中

my_lines = []
#line 52
for row_in in range(len(..... stuff)):
    
    ... your code

    #line 69
    print(newfile)  # <-- this could be called processed_csv_line
    # new code you need to add here
    processed_csv_line = newfile
    my_lines = my_lines.append(processed_csv_line)


output_file = open("_output.csv","w")
csv_writer = csv.writer(output_file)
# line 72
for row_n in my_lines:
     csv_writer.writerow(row_n)

#remember to close file after writing
output_file.close()

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

my_lines = []
#line 52
for row_in in range(len(..... stuff)):
    
    ... your code

    #line 69
    print(newfile)  # <-- this could be called processed_csv_line
    # new code you need to add here
    processed_csv_line = newfile
    my_lines = my_lines.append(processed_csv_line)


output_file = open("_output.csv","w")
csv_writer = csv.writer(output_file)
# line 72
for row_n in my_lines:
     csv_writer.writerow(row_n)

#remember to close file after writing
output_file.close()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文