【问题标题】:How to load a list, add an element to it and then store it again?如何加载列表,向其中添加元素然后再次存储?
【发布时间】:2021-04-27 19:36:33
【问题描述】:

我正在使用 Python 3.8

我想加载文件中没有整数值的列表,例如:[“a”,“b”,“c”],无论文件类型如何。然后我想在这个列表中添加一个元素 ex "d",所以最终列表将是 ["a", "b", "c", "d"]。

接下来,这个列表将被写入同一个文件中,替换里面的内容。这样,a 将拥有一个包含更新列表的干净文件。

这个过程会重复很多次。

我认为这是一个简单的过程,也许是,但我找不到方法。

【问题讨论】:

标签: python list process load write


【解决方案1】:

做你想做的事是可能的。但是您应该改用 le library pickle。 第一个导入图片

import pickle

为了保存变量,你可以使用这个

def saver(obj): #Pass the object you want to save
    pickle_file = open("data.pickle", "wb")
    pickle.dump(obj,pickle_file)
    pickle_file.close

然后加载:

def loader():

    pickle_file = pickle_file = open("data.pickle", "rb")
    data = pickle.load(pickle_file)
    pickle_file.close()
    return data

示例:

saver([1,2,3,4])
liste = loader()
print(liste)

【讨论】:

    【解决方案2】:

    如果我得到你,你需要从文件中读取一个内容,如 ["a", "b", "c"] ...并添加示例:d 然后将其重新保存在同一个文件中,所以我写下这段代码:

    fi = input("enter ur file name \n")
    elemnt = input("enter element you want to add exmple : d \n")
    list = []
    with open(fi, 'r', errors='ignore') as f:
        content = f.read()
        content = content.replace("[","").replace("]","").replace('"','')
        a, b, c = content.split(',')
        list.append(a)
        list.append(b)
        list.append(c)
        list.append(elemnt)
    print(list)
    open(fi, "w").write(str(list))
    

    【讨论】:

      【解决方案3】:

      谢谢大家。 我发现这个解决方案正是我所需要的。

      import csv
      
      try:
          with open("sales.csv") as f:
              print("File present")
              i = input("New Item: ")     
      
              with open('sales.csv', newline='') as csv_file:   
                  reader = list(csv.reader(csv_file))
                  for row in reader:
                      a = row
      
      
              a.append(i)
              print(type(a))
              print(a)
      
              with open('sales.csv', 'w') as csv_file:    
                  csv_writer = csv.writer(csv_file, delimiter=',')
                  csv_writer.writerow(a)
      
      except FileNotFoundError:
          print("File not present")
          i = [input("New Item: ")]   
          print(i)
      
          with open('sales.csv', 'w') as csv_file:    
              csv_writer = csv.writer(csv_file, delimiter=',')
              csv_writer.writerow(i)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-17
        • 2016-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-04
        相关资源
        最近更新 更多