On Python 3, it could look like:
with open("output.txt", "a") as file: # append to the file
print(*kF, sep=', ', file=file)
# etc...
I've added space after the comma for readability. See What does ** (double star) and * (star) do for parameters?
On Python 2, you could add from __future__ import print_function
at the top of your script and convert to string manually ", ".join(map(str, kF))
or just:
print(kFx, kFy, kFz, sep=', ', file=file)
You could use kF
object instead of kFx
, kFy
, kFz
e.g., a tuple/list:
kF = "kFx value", "kFy value", "kFz value"
or for readability, you could use collections.namedtuple
to create a custom class:
from collections import namedtuple
Point3D = namedtuple("Point3D", "x y z")
kF = Point3D("kFx value", "kFy value", "kFz value")
# -> Point3D(x='kFx value', y='kFy value', z='kFz value')
It enables kF.x
, kF.y
, kF.z
syntax. If you need a mutable object, you could use types.SimpleNamespace
:
from types import SimpleNamespace
kF = SimpleNamespace(x="kFx value", y="kFy value", z="kFz value")
kF.x += " modified"
# -> namespace(x='kFx value modified', y='kFy value', z='kFz value')
On Python 2, you could partially emulate it using class Point3D: pass
.
For a richer functionality, you could try attrs
package:
#!/usr/bin/fades
import attr # fades.pypi attrs
Point3D = attr.make_class("Point3D", ["x", "y", "z"])
kF = Point3D("kFx value", "kFy value", "kFz value")
kF.x += " modified"
# -> Point3D(x='kFx value modified', y='kFy value', z='kFz value')
To run this and other code examples that require third-party Python packages from PyPI, you could use fades
for convenience (to install, run: sudo apt-get install fades
). Though it is not necessary, you could just install dependencies manually instead: pip install attrs
(make sure to run your script with the same python
executable as pip
: head -1 $(command -v pip)
).
To print kF
to the file:
print(*attr.astuple(kF), sep=', ', file=file)
# -> kFx value modified, kFy value, kFz value
To save it in JSON format:
import json
with open("kF.json", "w", encoding='utf-8') as json_file: # overwrite the file
json.dump(attr.asdict(kF), json_file)
# -> {"x": "kFx value modified", "y": "kFy value", "z": "kFz value"}