如何将数组保存到文本文件并将其导回?

时间:2013-11-26 16:56:17

标签: python python-3.x

基本上,我想知道如何将我的数组从人员输入中获取数据保存到文本文件中,并在程序重新启动时自动导回到数组中。

编辑:此后,似乎保存并重新打开会将数据添加到相同的子阵列

我的代码:

import json
import time


datastore=[]
datastore = json.load(open("file.json"))
menuon = 1






def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")

    else:
        def add_data(users):
            for i in range(users):
                datastore.append([])
                datastore[i].append(input("Enter Name: "))
                datastore[i].append(input("Enter Email: "))
                datastore[i].append(input("Enter DOB: "))
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry[0])
        print("Email:  "+entry[1])
        print("DOB:  "+entry[2])
        print("\n")



def search_function(value):
  for eachperson in datastore:
      if value in eachperson:
          print_resource(eachperson)






while menuon == 1:        
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()


    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break


    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0

4 个答案:

答案 0 :(得分:1)

此模块可以执行您想要的操作:http://docs.python.org/3/library/pickle.html

一个例子:

import pickle

array = ["uno", "dos", "tres"]

with open("test", "wb") as f:
    pickle.dump(array, f)

with open("test", "rb") as f:
    unpickled_array = pickle.load(f)
    print(repr(unpickled_array))

Pickle序列化您的对象。实质上,这意味着它将其转换为可存储的格式,可用于重新创建原始的克隆。

如果您对更多信息感兴趣,请查看Wiki条目:http://en.wikipedia.org/wiki/Serialization

答案 1 :(得分:0)

Python文档有关如何处理文本文件以及其他文件进行读/写的美妙解释。这是链接:

http://docs.python.org/2/tutorial/inputoutput.html

希望它有所帮助!

答案 2 :(得分:0)

您需要以某种方式序列化数组以将其存储在文件中。序列化基本上只意味着变成一个线性的表示。就我们而言,这意味着一个字符串。有几种方法(csv,pickle,json)。我目前最喜欢的方法是json.dump()json.load()重新阅读。请参阅json docs

import json

def save_file():
    with open('datafile.json', 'w') as f:
        json.dump(datastore, f)

def load_file():
    with open('datafile.json', 'r') as f:
        datastore = json.load(f)

答案 3 :(得分:0)

使用JSON; Python有一个json module内置:

import json

datastore = json.load(open("file.json")) // load the file

datastore["new"] = "new value" // do something with your data

json.dump(datastore, open("file.json", "w")) // save data back to your file

您也可以使用Pickle来序列化字典,但JSON更适合小数据,并且使用简单的文本编辑器是人类可读和可编辑的,而Pickle是二进制格式。

我已经更新了你的代码以使用JSON和词典,它工作正常:

import json
import time

datastore = json.load(open("file.json"))
menuon = 1

def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")
    else:
        def add_data(users):
            for i in range(users):
                datastore.append({"name":input("Enter Name: "), "mail":input("Enter Email: "), "dob":input("Enter DOB: ")})
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry["name"])
        print("Email:  "+entry["mail"])
        print("DOB:  "+entry["dob"])
        print("\n")

def search_function(value):
  for eachperson in datastore:
    for i in eachperson.keys():
        if value in eachperson[i]:
            print_resource(eachperson)

while menuon == 1:        
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()

    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break

    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0