PYTHON - 将列表写入文件以便可以读取和写入

时间:2015-05-20 19:31:27

标签: python file

我是一名完整的新手程序员,正在制作一个基本的“会员”计划,让我有一些关于功能和列表的经验 到目前为止,我有this

#Club membership program with functions

Club = ['George','Isaiah','Alby','Jack']

#FUNCTIONS=========================================================================================================================================================================================================

def remove_member():
    """Function to delete member from the club"""
    print('The club members are:', Club)
    removal_member = str(input('Enter the name of the member you would like to remove:'))
    if removal_member in Club:
        Club.remove(removal_member)
    else:
        print('Member not found')
    print('The club members are now:', Club)

def add_member():
    """Funtion to add a member to the club"""
    new_member = str(input('Enter the name of the member you would like to add:'))
    Club.append(new_member)
    print('The club members are now:', Club)

def functions():
    print('''
   List of current funtions:
   1 = Remove a member
   2 = Add a member
   3 = trherjuthyjht\n''')

#MAIN==================================================================================================================================================================================================================

print('HELLO AND WELCOME TO THE CLUB MEMBERS PROGRAM')
print('The current members of the club are:', Club)
functions()


run_program = input('Would you like to carry out a function? (y/n):')
while run_program == 'y':
    function_no = int(input('enter the the number of the funtion you would like to execute:'))
    if function_no == 1:
        remove_member()
        run_program = input('Would you like to carry out a function? (y/n):')
        functions()
    else:
        if function_no == 2:
            add_member()
            run_program = input('Would you like to carry out a function? (y/n):')
            functions()

input('Thanks you for using the Club membership program, press enter to exit.')

我接下来要做的是扩展我的文件处理技能: 我希望能够将列表写入文件,因此每次打开或关闭程序时都可以检索列表

  1. 我该怎么做
  2. 我需要保存哪种文件类型,因为python将其识别为列表
  3. 任何进一步的帮助将不胜感激

2 个答案:

答案 0 :(得分:2)

您所描述的是数据序列化。格式很多。

例如,查看pickle模块。用法示例:

add_action('widgets_init', function() {                 
    register_widget('\a\b\c\whatever');
});

答案 1 :(得分:0)

以下是保存和加载列表的两个功能:

Club = ['George','Isaiah','Alby','Jack']
def saveClub(club):
    myfile= open('myfile.txt','w')
    for member in club:
        myfile.write(member+'\n')

def loadClub():
    newClub=[]
    with open('myfile.txt', 'r') as ins:
        for line in ins:
            newClub.append(line.rstrip('\n'))
    return newClub

saveClub(Club)
Club=loadClub()