【问题标题】:python output file formattingpython输出文件格式
【发布时间】:2013-12-05 02:06:00
【问题描述】:

我正在尝试编写一个程序,该程序使用 arcpy 计算表格,然后将表格转换为特定格式以供另一个程序读取。我得到的格式列在底部,枚举和逗号分隔。我希望格式只有第二个 2 字段由空格分隔,例如89.99 90.35 到目前为止,我的格式化尝试一直不成功,有人能指出我正确的方向吗?非常感谢

import arcpy,csv

table = "TABLE_OUTPUT2"
outfile = "TXT-TABLE"

fields = arcpy.ListFields(table)
field_names = [field.name for field in fields]

with open(outfile,'wb') as f:
    w = csv.writer(f)


for row in arcpy.SearchCursor(table):
    field_vals = [row.getValue(field.name) for field in fields]
    print field_vals
    w.writerow(field_vals)
del row

[1, 89.99999999446867, 90.3567070001462]

[2, 88.99999999460778, 89.83622323918551]

[3, 87.99999999448423, 89.1722770229037]

【问题讨论】:

  • 到目前为止你的文件的结果是什么?
  • w 更多的是用于逗号分隔的值,并且它只存在于开放块中
  • 我的最终解决方案见下文。感谢您的帮助

标签: python text format


【解决方案1】:
field_vals = [[1, 89.99999999446867, 90.3567070001462],
              [2, 88.99999999460778, 89.83622323918551], 
              [3, 87.99999999448423, 89.1722770229037]]
for field in field_vals:
    _, b, c = field
    print '{:.2f} {:.2f}'.format(b, c)


90.00 90.36
89.00 89.84
88.00 89.17

将变量名称bc 替换为更能代表其内容的名称。

如果您真的想对结果进行四舍五入(因此第一个数字是89.99 而不是90.00),请参阅this answer

【讨论】:

    【解决方案2】:

    我最终使用了以下代码来满足我的要求。但是我有一个奇怪的错误,所有文本都在 IDE 中打印到屏幕上,但文本文件中缺少 60 个值,即文本文件被截断 - 确实很奇怪..

    for row in arcpy.SearchCursor(table):
        field_vals = [row.getValue(field.name) for field in fields] #index the fields
        newlist2 = [field_vals[1], field_vals[2]] # reurn the required fields for azimuth and zenith
        newlist = str(newlist2[0]) + " " + str(newlist2[1]) + "\n" # format for trimble sodtware
    
        print newlist # Print and write the info
        outfile.write(newlist)
    del row
    

    【讨论】:

    • 截断是由于文件未正确关闭。通过使用 outfile.close() 修复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2020-01-16
    • 2021-01-03
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多