Timo 42
Timo 42

Reputation: 7

I want to write and read a list of a text file in python

I found a solutuion for writing my list in a txt file with this code:

with open("myfile.txt", "w") as f:
    string1 = "".join(map(str, LIST))
    f.write(string1)

the list looks something like this: [[(227, 489), 10, (255, 255, 255)][(227, 489), 10, (255, 255, 255)][(227, 489), 10, (255, 255, 255)]]

but if i want to read the list with this code:

with open("myfile.txt", "r") as f:
    circles = [f.read()]
    print(circles)

everything is in "" and the error is: IndexError: string index out of range

here is the whole code of the program:

import pygame
import os

pygame.init()

pen_color = (255, 255, 255)
WIDTH = 1000
HEIGHT = 1000
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

# COLORS
GREEN_IMG = pygame.image.load(os.path.join("Colors", "green.png"))
GREEN = pygame.transform.scale(GREEN_IMG, (50, 50))
pen_size = 10

circles = []

def draw_colors():
    global pen_color
    WIN.blit(GREEN, (900, 900))
    mouse = pygame.mouse.get_pos()
    mouse_pressed = pygame.mouse.get_pressed()
    if mouse_pressed[0]:
        if 900 <= mouse[0] <= 950 and 900 <= mouse[1] <= 950:
            pen_color = (0, 255, 0)

def handle_drawing():
    mouse_pressed = pygame.mouse.get_pressed()
    if mouse_pressed[0]:
        mouse_pos = pygame.mouse.get_pos()
        circles.append([mouse_pos, pen_size, pen_color])
    for circle in circles:
        print(circles)
        pygame.draw.circle(WIN, circle[2], (circle[0][0], circle[0][1]), circle[1])
        print(pen_color)
    

def key_control():
    global pen_size
    global circles
    keys = pygame.key.get_pressed()
    if keys[pygame.K_b]:
        pen_size += 1
    if keys[pygame.K_s]:
        with open("myfile.txt", "w") as f:
            string1 = "".join(map(str,circles))
            f.write(string1)
    if keys[pygame.K_o]:
        with open("myfile.txt", "r") as f:
            circles = [f.read()]
            print(circles)

def main():
    clock = pygame.time.Clock()
    while True:
        clock.tick(60)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                break
        key_control()
        handle_drawing()
        draw_colors()
        pygame.display.update()

main()

Upvotes: 0

Views: 1135

Answers (3)

Daweo
Daweo

Reputation: 36873

I suggest considering usage of pickle built-in module. You can use it following way for writing

import pickle
data = [1,(2,3)]
with open('save.p','wb') as f:
    pickle.dump(data, f)

and following way for reading

import pickle
with open('save.p','rb') as f:
    data = pickle.load(f)
print(data)  # [1, (2, 3)]

Beware that pickle is not secure (read linked docs for more information). pickle is one of way of providing persistent storage if it doesn not suit your needs you might try searching for another method - look for persistent storage python

Upvotes: 0

Deven Ramani
Deven Ramani

Reputation: 781

As pickle is not secure you can use json format

dump/dumps: Serialize
load/loads: Deserialize

https://docs.python.org/3/library/json.html

Code:

>>> import json
>>> l = [1,2,3,4]
>>> with open("test.txt", "w") as fp:
...     json.dump(l, fp)
...
>>> with open("test.txt", "r") as fp:
...     b = json.load(fp)
...
>>> b
[1, 2, 3, 4]

Upvotes: 1

Jakemoyo
Jakemoyo

Reputation: 181

If you are wanting to write a python list to a txt file and then read it back in as a list you need to do something like this.

Write it with some delimiter.

with open("myfile.txt", "w") as f:
    string1 = ",".join(map(str, LIST))
    f.write(string1)

And then read it in and split it on that same delimiter.


with open("myfile.txt", "r") as f:
    text = f.read()
    my_list = text.split(',')

Upvotes: 0

Related Questions