【问题标题】:Saving x,y coordinates in python在python中保存x,y坐标
【发布时间】:2013-05-24 06:14:11
【问题描述】:

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

谢谢

输出示例: …

100 23

112 18

133 67

221 99

232 100

【问题讨论】:

  • some_file.write(output_data)

标签: python string save


【解决方案1】:

假设coordinatesxy 对的序列

import csv

with open('out.txt', 'wb') as f:
    csv.writer(f, delimiter=' ').writerows(coordinates)

【讨论】:

    【解决方案2】:

    例如使用普通的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)
    

    【讨论】:

    • .writerows 更适合csv 解决方案
    • 对。我会保持原样 - 你的答案中有它,所以 OP 可能对这个问题有更好的看法
    • 好吧,+1 建议将JSON 作为可读的替代方案(但是您使用了错误的dump,应该是dump 而不是dumps
    【解决方案3】:

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

    python *your_code.py* | tee *output_file*
    

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

    【讨论】:

    • 他也不需要打印到控制台
    猜你喜欢
    • 2022-01-19
    • 2021-08-29
    • 2014-02-26
    • 1970-01-01
    • 2022-11-13
    • 1970-01-01
    • 2023-04-04
    • 2016-06-04
    • 2013-05-05
    相关资源
    最近更新 更多