【问题标题】:Formatting output csv files格式化输出 csv 文件
【发布时间】:2014-03-17 20:07:57
【问题描述】:

我能否就以下问题获得一些帮助。我似乎无法发现我的代码哪里出错了。我的代码中有 2 个输出 csv 文件。第一个产生正确的格式,但第二个没有:

First output file (fileB in my code)
A,B,C
D,E,F

Second output file (fileC in my code)
A,B,
  C
D,E,
  F

这是我的代码:

file1 = open ('fileA.csv', 'rt', newline = '')

shore_upstream = open('fileB.csv', 'wt', newline = '')
shore_downstream = open('fileC.csv', 'wt', newline = '')

for line in file1:
    first_comma = line.find(',')
    second_comma = line.find(',', first_comma + 1)
    start_coordinate = line [first_comma +1 : second_comma]
    start_coordinate_number = int(start_coordinate)
    end_coordinte = line [second_comma +1 :]
    end_coordinate_number = int (end_coordinte)
    upstream_start = start_coordinate_number - 2000
    downstream_end = end_coordinate_number + 2000
    upstream_start_string = str(upstream_start)
    downstring_end_string = str(downstream_end)
    upstream_shore = line[:first_comma]+','+ upstream_start_string + ',' + start_coordinate 
    shore_upstream.write(upstream_shore + '\n')
    downstream_shore = line[:first_comma]+ ','+ end_coordinte + ',' + downstring_end_string
    shore_downstream.write(downstream_shore + '\n')

file1.close()
shore_upstream.close()
shore_downstream.close()

顺便说一句,我使用的是 python 3.3。

【问题讨论】:

  • 您没有使用csv 模块有什么原因吗?

标签: python text formatting


【解决方案1】:

您的变量 end_coordinte 可能包含非十进制字符,并且可能在末尾包含 \n\t,从而导致该输出。

最简单的解决方案可能是将这些字符串评估为一个数字,然后将它们作为字符串打印回来。 替换:

upstream_shore = line[:first_comma]+','+ upstream_start_string + ',' + start_coordinate
downstream_shore = line[:first_comma]+ ','+ end_coordinte + ',' + downstring_end_string

作者:

upstream_shore = line[:first_comma]+','+ upstream_start_string + ',' + str(start_coordinate_number) 
downstream_shore = line[:first_comma]+ ','+ str(end_coordinate_number) + ',' + downstring_end_string

并注意line[:first_comma] 输出,因为它也可能包含您不期望的字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    相关资源
    最近更新 更多