2

我在 for 循环中生成数百行(x,y 坐标)输出。在流程结束时将它们保存到 txt 文件中的简单方法是什么?

谢谢

输出示例:……</p>

100 23

112 18

133 67

221 99

232 100

…</p>

4

3 回答 3

2

例如常规写入

with open('filename', 'w') as fh:
    for x, y in coodrinates: 
        fh.write('{} {}\n'.format(x, y))

或使用JSON

with open('filename', 'w') as fh:
    json.dump(coordinates, fh, indent=1)

或使用CSV

with open('filename', 'w') as fh:
    spamwriter = csv.writer(fh)
    for t in coordinates:
        spamwriter.writerow(t)
于 2013-05-24T06:17:34.637 回答
2

假设coordinatesx,y对的序列

import csv

with open('out.txt', 'wb') as f:
    csv.writer(f, delimiter=' ').writerows(coordinates)
于 2013-05-24T06:20:25.727 回答
0

如果您在 Unix 环境中。你可以运行这个命令:

python *your_code.py* | tee *output_file*

输出将打印到控制台和 *output_file*。

于 2013-05-24T06:17:11.413 回答