简体   繁体   English

无法将列表写入文本文件

[英]Can't write list into a text file

I'm getting issues saving a list[str] into a text file in Python.我在将列表 [str] 保存到 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.所以我有一些数字图像,我正在通过 CNN 运行并输出到文本文件中,以便稍后阅读它们。 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.问题是我在列表中尝试了一些逻辑,因为我需要每个图像的 output 在同一行,然后换行以获得新图像 output。 This logic works fine in one function and gets me an output in the text file but fails in this one.此逻辑在一个 function 中运行良好,并在文本文件中为我提供了 output 但在此失败。

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.我尝试在 for 循环外部声明 predict_list 以迭代图像,并在 for 循环内部声明迭代图像文件夹。 (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) (通常每个文件夹 5 个图像;意味着每个内部 for 循环 5 次迭代。然后开始外部 for 循环的新循环,该循环将 go 通过另一个包含其他图像的目录)

predict_digit(model) in Cnn.py: Cnn.py 中的 predict_digit(model):

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.调用 function 并尝试获取保存的文本文件中的值并将它们输出到控制台。 (console output isn't necessary I just need the list to save in the text file) (不需要控制台 output 我只需要将列表保存在文本文件中)

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 extract_names() 也在 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在 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.我意识到输出到文本文件是非常丑陋的编程,但不幸的是,由于系统 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.这可能是我的一个非常蹩脚的错误,但经过漫长的一周工作,我的脑力似乎让我失望了。

You can use the pickle module to save and restore Python objects.您可以使用pickle 模块来保存和恢复 Python 对象。

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.如果您更喜欢在磁盘上具有人类可读的格式和/或您需要跨不同语言的可移植性,您可以使用json 模块代替。 See the documentation's comparison between pickle and json .请参阅文档中 pickle 和 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

@Moudhaffer Bouallegui as you want it to save in text file, use the below code: @Moudhaffer Bouallegui 因为您希望它保存在文本文件中,请使用以下代码:

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM