2016-01-05 240 views
-1

我在教自己编程,使用Python作为我的首选武器。Python:将列表写入.csv文件

我已经学会了一些基本知识,并决定为自己设定一个询问用户列表名称,将名称添加到列表中,然后将名称写入.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() 
+6

我认为你正在寻找[codereview.se] – jonrsharpe

+0

@jonrsharpe谢谢。 –

回答

0

我试着写下您的需求:

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

首先,我会强烈建议您阅读一个Python ST环操作和格式化教程,如Google Developer Tutorial。当您了解基本操作时,请查看official documentation以查看Python中可用的字符串处理方法。

你的逻辑写的代码是正确的,但有两个无意义线:

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

这是没有必要降低“完成”,因为它已经是小写。

  • 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) 
    

    要知道,有许多方法,以满足您的需求,以不同的逻辑和方法。