1

I need to create a file to save some variables; I have this

# variables 
A = 2
B = 34
C = "foo"
file = open("filename.txt", "w")
file.write(A, "/", B, "/", C)
file.close()

However, I'm not sure is this is the best way, or at least, the best 'Pythonic' way to write in a file. I do not neither know if / is the best item to disjoin to then read it or it is better to do for example

file.write(f"A={A}/nB={B}/nC={C}")

That is the princiapl problem: I do not know how to, after writing, read multiple variables and its best way to do that. In the reading file, I would like to have something like this:

file = open("filename.txt", "r")
# reading variables
# variables initialized: A=2, B=34, C="foo"

So, to recap, I would appreciate some help to find out: 1) Best format to write in a file 2) How to read multiple variables in that file and initialize them P.D: it doesn't have to be a .txt but it's the default format I'm advised to use.

Thank you!

Omar
  • 1,029
  • 2
  • 13
  • 33
  • 1
    This would be helpful, https://stackoverflow.com/questions/36559580/what-is-the-purpose-of-a-context-manager-in-python/36559849 – sushanth Jun 03 '20 at 16:24
  • 5
    There are many serialization methods out there and what is the "best" depends on how you plan to use the data later. Python's own `pickle` is a good choice for covering a wide range of data structures for python-only use. JSON is a good general purpose serializer. CSV is popular for tabular data. A SQL db is great for complex tabular data with rich query capability. XML / HTML for structured text. The list goes on...! – tdelaney Jun 03 '20 at 16:25
  • 1
    If you have some free time i recommend you to learn sqlite and json – Hoxha Alban Jun 03 '20 at 16:27

2 Answers2

2

To answer your first question, I think the best format to use is a widely-used standard like JSON, XML or CSV to store your data to file.

Firstly, this will mean you have less logic to implement yourself - all the serialization and deserialization can be done through standard libraries that are widely available in python. Secondly, libraries exist in most programming languages to parse these files, so you won't ever find yourself having to reimplement this logic if you ever find yourself having to pull this data into another application. Finally, since these libraries are used so widely, they are heavily optimized and so are unlikely to cause you any performance problems.

I'd recommend JSON myself as the python libraries make using it so easy. Here's an example of what writing and reading JSON from file looks like in python:

import json

A = 2
B = 34
C = "foo"

# Write to file
obj = {
    'A': A
    'B': B
    'C': C
}
with open("filename.txt", "w") as f:
    json.dump(obj, f)

# Read from file
with open("filename.txt", "r") as f:
    obj2 = json.load(f)

A = obj2['A']
B = obj2['B']
C = obj2['C']
Rob Streeting
  • 1,675
  • 3
  • 16
  • 27
1

You are correct. That is indeed bad design (as it is not OS agnostic).

import os

dir = os.path.join('foo', 'bar') 
print(dir)  # prints the proper dir format in Windows, OSX, Linux

Furthermore, the way your write your file is fine, but it does not close the file in case any errors occur prior to f.close(). Thus, you should use the following:

with open(dir, 'r') as f:
    data = f.read()

The with statement is a block execution context manager that closes the file no matter what occurs within it's scope. Sometimes, using the simple f.open is necessary, but this is usually enclosed in a try/except.

justahuman
  • 607
  • 4
  • 13