Reputation: 442
In my document I would like to add scores to a chosen line using:
file = open('scores.txt', 'a')
because I don't want to add all the lines to a list and change that one line.
I'm basically asking if you can add something to .write()
or .writelines()
to choose the line that it writes onto. If not, any other ways? If not, maybe a simple way of adding to a list then changing a line.
basically what the txt document looks like:
User 1 scores:
15,
User 2 Scores:
20,
Upvotes: 0
Views: 222
Reputation: 638
The best way to store data to store some kind of user informations is Serialization. You have several modules including Pickle (which serialize the object into a binary file, and later can deserialize this object by reading the file, giving you the exact same object as it was before serialization), or Json.
If you're looking for a good solution, but still want to be able to clearly read data (Since Pickle is storing the data as a binary entity object, you can't read it clearly), use JSON.
It's very simple for this basic use :
If you have for example this same structure as you showed before:
User 1 scores:
15,
User 2 scores:
20,
You can make it as a dictionary, for example like that:
scores = {
'User 1': 15,
'User 2': 20,
}
Which makes it even easier to edit and use, since to access the User 1 score, all you need to type is scores['User 1']
.
Now, for the serialization part of this dictionary, to save it into a file, you can obtain a serialized string representing the dict using the json.dumps(<your array>)
function. Used like that:
import json
dictionary = { 'User 1': 15, 'User 2': 20 }
print(json.dumps(dictionary))
The print will show you how it's represented. As a JSON compliant file.
You just need a simple file.write()
to save it, and a file.read()
to retrieve it.
(After test, using json.dumps on your example give me that: {"User 2": 20, "User 1": 15}
)
To retrieve that data, you'll need to use the json.loads(<json string>)
function.
import json
# As you can see, string representation of json.
dictionary = json.loads("{"User 2": 20, "User 1": 15}")
Your dict is now loaded & saved !
More infos on File IO here: http://www.tutorialspoint.com/python3/python_files_io.htm
More infos on JSON Python native API here: https://docs.python.org/3/library/json.html
Hope that helps !
EDIT:
For your information, Python native file IO module only give 1 function to change the position of the read buffer in the file, and that function is file.seek()
function, that moves you into a specific byte in the file. (you need to pass the byte address as a function parameter, for example file.seek(0, 0)
will position you at the beginning of the file).
You can get your position in the file using file.tell()
function.
Upvotes: 1