【问题标题】:Python: Writing lists to .csv file [closed]Python:将列表写入 .csv 文件 [关闭]
【发布时间】:2016-01-05 22:50:31
【问题描述】:

我正在自学编程,使用 Python 作为我最初选择的武器。

我已经学习了一些基础知识,并决定为自己设定一个挑战,即向用户询问姓名列表,将姓名添加到列表中,然后最后将姓名写入.csv 文件。

下面是我的代码。有用。

我的问题是你会做哪些不同的事情,即如何改进这段代码的可读性和效率。你会以不同的方式处理这种情况,以不同的方式构建它,调用不同的函数吗?我对更有经验的程序员的反馈很感兴趣,并且非常感激。

特别是,我发现某些部分很笨拙;例如必须向用户指定数据输入所需的格式。但是,如果我只是简单地请求不带逗号的数据(姓名年龄位置),那么每条记录在写入.csv 时,最终只会成为每个单元格一条记录(Excel)——这不是预期的结果。

#Requesting user input. 
guestNames = input("Please enter the names of your guests, one at a time.\n"\
    "Once you have finished entering the information, please type the word \"Done\".\n"\
    "Please enter your names in the following format (Name, Age, Location). ").capitalize()

guestList.append(guestNames)

while guestNames.lower() != "done".lower() :
    guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()
    guestList.append(guestNames)
    number += 1

#Sorting the list. 
guestList.sort()
guestList.remove("Done")

#Creating .csv file. 
guestFile = open("guestList.csv","w")
guestFile.close()

#Writing to file. 
for entries in guestList :
    guestFile = open("guestList.csv","a")
    guestFile.write(entries)
    guestFile.write("\n")
    guestFile.close()

【问题讨论】:

标签: python list csv


【解决方案1】:

我试着写下你的要求:

  1. 根据输入字符串的结构(无论如何)解析输入字符串并将结果保存到列表中
  2. 将结果格式化为 CSV 格式的字符串
  3. 将字符串写入 CSV 文件

首先,我强烈建议您阅读 Python 字符串操作和格式化教程,例如 Google Developer Tutorial。了解基本操作后,看看official documentation,看看Python中可用的字符串处理方法。

你写代码的逻辑是对的,但是有两行没有意义:

  1. while guestNames.lower() != "done".lower()

“done”已经是小写了,所以不必降低它。

  1. for entries in guestList : guestFile = open("guestList.csv","a")

在这里,您在每个循环中打开和关闭 questList.csv,这是无用且成本高昂的。您可以在开头打开文件,然后使用 for 循环保存所有行,并在最后关闭它。

这是一个使用相同逻辑和不同输入格式的示例:

print('some notification at the beginning')

while true:
    guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()

    if guestNames == 'Done':
        # Jump out of the loop if user says done
        break
    else:
        # Assume user input 'name age location', replace all space with commas
        guestList.append(guestNames.replace(' ', ','))
        number += 1

guestList.sort()

# the with keyword will close the guestFile at the end
with open("guestList.csv","w") as guestFile:
    guestFile.write('your headers\n')
    for entries in guestList:
        guestFile.write('%s\n' % entries)

请注意,满足您的需求的方法有很多种,它们具有不同的逻辑和方法。

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2016-09-02
    • 2016-03-26
    相关资源
    最近更新 更多