从用户输入和输出到CSV生成嵌套列表

2024-10-03 19:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个编程新手(使用python3atm),我的第一个程序需要获取4个用户输入(在一个带有指定转义字符的无限循环中),并最终将它们写入一个带有头的CSV文件中。要么是这样,要么是每4个单元格将数据写入一个新行,通过我两天的谷歌搜索,我还不知道该怎么做。在

我让程序处理输入并将其写入CSV,但是它只在循环的每次迭代中覆盖第一行中的数据。在

以下是我目前所掌握的情况

count = 0
while (1):

    variable1 = str(input('Enter data here: '))
    variable2 = str(input('Enter data here: '))
    variable3 = str(input('Enter data here: '))
    variable4 = str(input('Enter data here: '))

    save = [variable1,variable2,variable3,variable4]
    file = open('file.csv', 'w', newline='')
    csv_write = csv.writer(save, delimiter=',')
    file.close()
    count += 1

我的问题是理解(可能理解)如何获取每个循环迭代中完成的输入,并将数据存储到其自己的嵌套列表段中。有点像

^{pr2}$

然后将嵌套列表写入CSV。在

我希望我能够很好地描述我的需求和对这个概念缺乏理解。:\


Tags: csv数据inputdataheresavecountfile
2条回答

  count = 0
  f = open('file.csv', 'w')
  w = csv.writer(f)
  allsaves = []
  while True:
      variable1 = str(input('Enter data here: '))
      variable2 = str(input('Enter data here: '))
      variable3 = str(input('Enter data here: '))
      variable4 = str(input('Enter data here: '))

      save = [variable1,variable2,variable3,variable4]
      w.writerow(save)
      allsaves.append(save)

否则你会有更好的结局时间:-)在

一个只运行两次循环的简单解决方案。。。在

import csv

with open('file.csv', 'w') as csvfile:
 csv_write = csv.writer(csvfile)
 count = 0

 while (count<2):
  variable1 = str(input('Enter data here: '))
  variable2 = str(input('Enter data here: '))
  variable3 = str(input('Enter data here: '))
  variable4 = str(input('Enter data here: '))
  csv_write.writerow([variable1, variable2, variable3, variable4])
  count += 1

相关问题 更多 >