我在for循环中生成数百行(x,y坐标)输出。在流程结束时将它们保存到txt文件的简单方法是什么?
由于
输出示例: ...
100 23
112 18
133 67
221 99
232 100
...
答案 0 :(得分:2)
假设coordinates
是一系列x
,y
对
import csv
with open('out.txt', 'wb') as f:
csv.writer(f, delimiter=' ').writerows(coordinates)
答案 1 :(得分:1)
例如使用常规write
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)
答案 2 :(得分:0)
如果您在Unix环境中。您可以运行此命令:
python *your_code.py* | tee *output_file*
输出将打印到控制台和* output_file *。