1

I have a script written in python which I am running on ubuntu. I would like the output of this command to be directed into the file.

print str(kFx) + ',' + str(kFy) + ',' + str(kFz)

I would ideally use the python.py > file.txt but the script has some interactive parts which I won't be able to use if I redirect the output to a file.

I tried changing the code to this but I get syntax errors. I literally use python for the first time so excuse my lack of knowledge.

print (str(kFx) + ',' + str(kFy) + ',' + str(kFz) , file=open("output.txt", "a"))

Any ideas on how to do that?

Thank you, Alex

Alex
  • 23
  • 1
  • 6
  • 1
    You are probably using Python 2. Either change the print to [`print >> open("output.txt", "a"), str(kFx) + ',' + str(kFy) + ',' + str(kFz)`](https://docs.python.org/2/reference/simple_stmts.html#the-print-statement) or put a [`from __future__ import print_function`](https://www.python.org/dev/peps/pep-3105/) at the top of your code file if you want to use the `print()` function (instead of the statement). – dhke Mar 07 '17 at 21:31

3 Answers3

1

you can open the file with file=open("output.txt", "a")) like you did. then instead of printing you would use

file.write(str(kFx) + ',' + str(kFy) + ',' + str(kFz))

becasue you opened the file in append mode (denoted by the "a" in open) it would add this string to the end of the file. you might also need to add a new line after your string:

file.write("\n")

when you are done writing:

file.close()
Buzz
  • 1,877
  • 21
  • 25
  • To close the file even if an exception happens, you could use `with`-statement. Also, you could call print() function, to format the input, without calling `str()` and concatinating the strings manually. – jfs Mar 08 '17 at 11:14
  • Followed your instruction worked perfectly . Thank you :) – Alex Mar 09 '17 at 22:51
1

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"}
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

If you use with-keyword; the file-stream will only stay open inside the block. Then you dont have to remember closing it when you are done.

with open('test.output', 'w') as f:
    f.write('{0},{1},{2}\n'.format(kFx, kFy, kFz))

If you meant to append to file like echo "test" >> test.txt and not echo "test" > test.txt Then just change the open mode to 'a' instead of 'w'

David Bern
  • 778
  • 6
  • 16
  • 1
    `'\n'` is missing. You don't need to call `str()` manually, `format()` does it for you. You may omit digits in the format: `'{},{},{}\n'.format(kFx, kFy, kFz)`. – jfs Mar 08 '17 at 11:18
  • 1
    Good eye thanks for correcting me because I didn't know what 'a' option was in python. Thank you :) – Alex Mar 09 '17 at 22:52