0

I'm using Python 3.8

I want to load a list of no integer value that is in a file ex: ["a", "b", "c"], no matter the kind of the file. Then I want to add to this list an element ex "d" so the final list would be ["a", "b", "c", "d"].

Next, this list will be written in the same file replacing what was inside. In this way a will have a clean file with the updated list.

This process will be repeated many times.

I thought it was a simple process and maybe it is, but I can't find a way.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

3 Answers3

1

Doing what you want is possible. But you shoul use instead le library pickle. First import picle

import pickle

For saving the variable you can use this

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

Then to load :

def loader():

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

Exemple:

saver([1,2,3,4])
liste = loader()
print(liste)
Fredericka
  • 296
  • 1
  • 7
0

if i get you , you need to read from the file a content like ["a", "b", "c"] ... and add exemple : d then re-save it in the same file so i write this code :

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

enter image description here

Moetaz Brayek
  • 259
  • 2
  • 9
0

thank you all. I found this solution that is actually what I needed.

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)