user1212200
user1212200

Reputation: 353

Saving x,y coordinates in python

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

Answers (3)

Jakub M.
Jakub M.

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

jamylak
jamylak

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

Roger
Roger

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

Related Questions