Moudhaffer Bouallegui
Moudhaffer Bouallegui

Reputation: 126

Can't write list into a text file

I'm getting issues saving a list[str] into a text file in Python.

So I have certain images of digits that I'm running through a CNN and outputing into a text file so that I could read them later on. The issues is that I tried some logic with the list because I need each image's output to be on the same line and then line break for a new image output. This logic works fine in one function and gets me an output in the text file but fails in this one.

I'm including the snippets neeeded to get a clear idea but if you still need further clarification let me know.

I tried declaring the predict_list outside the for loop for iterating through images and inside the for loop that's iterating through folders of images. (Generally 5 images per folder; meaning 5 iterations per inner for loop. Then begins a new cycle for the outer for loop that'll go through another directory containing other images)

predict_digit(model) in Cnn.py:

def predict_digit(model):
    for folder in glob.glob(rf"C:\Users\lenovo\PycharmProjects\SoftOCR_PFE\digit_segment"):
        print(rf"digit_segment\folder: {folder}")
        predict_list = []
        for image in glob.glob(rf"{folder}\*.png"):
            # Read image
            img = cv2.imread(image)
            # Grayscale
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            # Resized image
            resized = cv2.resize(gray, (28, 28), interpolation=cv2.INTER_AREA)
            # Dividing by 255 to get pixel values between 0-1
            newimg = tf.keras.utils.normalize(resized, axis=1)
            newimg = np.array(newimg).reshape(-1, 28, 28, 1)
            # Getting a prediction
            prediction = model.predict(newimg)
            print(np.argmax(prediction))
            predict_list.append(prediction)
        predict_list.append('\n')
        with open(f'saved_marks.txt', 'w+') as filehandle:
            for listitem in predict_list:
                filehandle.write(f'{listitem}')

calling the function and attempting to get the values inside the saved text file and outputing them to the console. (console output isn't necessary I just need the list to save in the text file)

predict_digit(loaded_model)
# Using readlines() to gather marks in one list and print them to console
file1 = open('saved_marks.txt', 'r')
grade_prediction = file1.readlines()
count = 0
# Strips the newline character
for line in grade_prediction:
    count += 1
    print("Line{}: {}".format(count, line))

It's working fine for this process; extract_names() also inside Cnn.py

def extract_names():
    # Adding custom options
    folder = r"C:\Users\lenovo\PycharmProjects\SoftOCR_PFE\names"
    custom_config = r'--oem 3 --psm 6'
    words = []
    for img in glob.glob(rf"{folder}\*.png"):
        text = pytesseract.image_to_string(img, config=custom_config)
        words.append(text)
    all_caps = list([s.strip() for s in words if s == s.upper() and s != 'NOM' and s != 'PRENOM'])

    no_blank = list([string for string in all_caps if string != ""])
    with open('saved_names.txt', 'w+') as filehandle:
        for listitem in no_blank:
            filehandle.write(f'{listitem}\n')

Calling and outputing in main.py

extract_names()
# Using readlines() to gather names in one list and print them to console
file = open('saved_names.txt', 'r')
names_prediction = file1.readlines()
count = 0
# Strips the newline character
for line in names_prediction:
    count += 1
    print("Line{}: {}".format(count, line.strip()))
file.close()

I realize outputing to text files is very ugly programming but unfortunately I'm obliged to do so for the moment due to uncompatibility issues with the system gui. It's probably a very lame mistake on my part but after a long week of work, my brainpower sadly seems to fail me.

Upvotes: 0

Views: 561

Answers (2)

singhV
singhV

Reputation: 157

@Moudhaffer Bouallegui as you want it to save in text file, use the below code:

list1 = ['1', '2', '3']
with open("file.txt", "w") as output:
    output.write(str(list1))

Now if you want to retrieve it back:

file=open("file.txt","r")
s=""
for line in file:
    s=s+line

import ast
x=ast.literal_eval(s)
print(x) #['1', '2', '3']

Upvotes: 0

stfwn
stfwn

Reputation: 362

You can use the pickle module to save and restore Python objects.

import pickle
foo = [1,2,3]
# 'wb' stands for 'write bytes'
with open('foo.pkl', 'wb') as f:
    # Pickle (serialize) foo into bytes and save to disk
    pickle.dump(foo, f)

# 'rb' is 'read bytes'
with open('foo.pkl', 'rb') as f:
    # Unpickle (deserialize) the bytes back into a Python object in memory
    bar = pickle.load(f)
print(foo == bar) # True

If you prefer to have a human-readable format on disk and/or you need portability across different languages you can use the json module instead. See the documentation's comparison between pickle and json.

import json
foo = [1,2,3]
with open('foo.json', 'w') as f:
    # Serialize foo into a valid JSON string and save to disk
    json.dump(foo, f)

with open('foo.json', 'r') as f:
    # Deserialize the JSON back into a Python object in memory
    bar = json.load(f)
print(bar)
print(foo == bar) # True

Upvotes: 2

Related Questions