Reputation: 353
I am generating hundreds of lines (x,y coordinates) output in a for loop. What would be the easy way to save them into a txt file at the end of the process?
Thanks
Example of output: …
100 23
112 18
133 67
221 99
232 100
…
Upvotes: 2
Views: 6165
Reputation: 33857
For example with regular write
with open('filename', 'w') as fh:
for x, y in coodrinates:
fh.write('{} {}\n'.format(x, y))
or with JSON
with open('filename', 'w') as fh:
json.dump(coordinates, fh, indent=1)
or with CSV
with open('filename', 'w') as fh:
spamwriter = csv.writer(fh)
for t in coordinates:
spamwriter.writerow(t)
Upvotes: 2
Reputation: 133634
Assuming coordinates
is a sequence of x
, y
pairs
import csv
with open('out.txt', 'wb') as f:
csv.writer(f, delimiter=' ').writerows(coordinates)
Upvotes: 2
Reputation: 450
If you are in a Unix environment. You could run this command:
python *your_code.py* | tee *output_file*
The output will print to console and the *output_file* as well.
Upvotes: 0