Arbys
Arbys

Reputation: 35

Saving lists into .txt - python

I am quite new to programming and I am coding simple game in Python (case opening from CSGO). I have list with some things in it - example ["P250 - Iron Clad", "P2000 - Imperial Dragon"] and I am searching for the best way to save it to txt file after game closes, and then again read it after game starts. I have tried soo many ways but it still doesn't work rly. Can you suggest me some idea? Thanks. :-)

my current save code:

with open("userskins.txt", "w") as text_file:
    text_file.write(str(skinsall))

my current load code /DOESN'T WORK/ I don't know how to convert this type of str (more words at one item) into list

file2 = open("userskins.txt", "r")
skinsall = (file2.read())

Upvotes: 0

Views: 2290

Answers (1)

sudo
sudo

Reputation: 5784

Assuming you want to save a list of strings, both of which are JSON-serializable (along with booleans, many numeric types, and dictionaries), JSON is a popular way to do this.

Saving: Open a write file with write_file = open(filename, "w"). Save as JSON with json.dump(your_list, write_file).

Loading: Open a read file with read_file = open(filename, "r"). Load JSON with your_list = json.load(read_file).

Documentation: https://docs.python.org/3.6/library/json.html

A few other formats you could try, each with their own pros/cons: CSV, XML, Python's native format (repr(your_list)).

Upvotes: 1

Related Questions