【问题标题】:Unexpected Blank lines in python outputpython输出中出现意外的空行
【发布时间】:2010-06-04 05:50:38
【问题描述】:

我有一些代码通过字典运行并以 CSV 格式输出其中的值。奇怪的是,我得到了几个空行,其中所有字典条目的所有输出都是空白的。我已经阅读了代码并且无法理解除了可以输出逗号行之外的任何内容。空行应该有值,所以额外的 \n 不是原因。谁能告诉我为什么我会得到空白行?其他时候我运行丢失的行出现。

缺少一行:

6415, 6469, -4.60, clerical, 2, ,,,joe,030193027org,joelj,030155640dup

使用python 2.6.5

代码:

      tfile = file(path, 'w')
      tfile.write('Rec_ID_A, Rec_ID_B, Weight, Assigned, Run, By, On, Comment\n')
      rec_num_a = 0

      while (rec_num_a <= max_rec_num_a):
        try:
            value = self.dict['DA'+str(rec_num_a)]
        except:
            value = [0,0,0,'rejected']
        if (value[3]!='rejected'):
            weightValue = "%0.2f" % value[2]
            line = value[0][1:] + ', ' + value[1][1:] + ', ' + weightValue \
                             + ', ' + str(value[3]) + ', ' + str(value[4]) 
            if (len(value)>5):
                line = line + ', ' + value[5] + ',' + value[6] + ',' + value[7]
            (a_pkey, b_pkey) = self.derive_pkeys(value)
            line = line + a_pkey + b_pkey
             tfile.write( line + '\n')
        rec_num_a +=1            

样本输出

6388, 2187, 76.50, clerical, 1, ,,,cameron,030187639org,cameron,030187639org
6398, 2103, 70.79, clerical, 1, ,,,caleb,030189225org,caldb,030189225dup
6402, 2205, 1.64, clerical, 2, ,,,jenna,030190334org,cameron,020305169dup
6409, 7892, 79.09, clerical, 1, ,,,liam,030191863org,liam,030191863org

6416, 11519, 79.09, clerical, 1, ,,,thomas,030193156org,thomas,030193156org
6417, 8854, 6.10, clerical, 2, ,,,ruby,030193713org,mia,020160397org
6421, 2864, -0.84, clerical, 2, ,,,kristin,030194394org,connou,020023478dup
6423, 413, 75.63, clerical, 1, ,,,adrian,030194795org,adriah,030194795dup

【问题讨论】:

  • 先学会使用内置的字符串格式化函数,docs.python.org/library/stdtypes.html#string-formatting
  • @fuzzy:这些都在 Python 3.0 中消失了,无论如何,如果你要选择一些东西,我会说迭代风格 ;-) Martlark,这是 for rec_num_a in xrange(max_rec_num_a) 的理想场所
  • 我使用的字符串格式是否错误?我没有使用内置的 csv 模块,因为这不是我的代码。
  • @fuzzy,@David,您仍然可以使用带有占位符的 str.format()。绝对比一堆串联好。
  • 不要重新发明轮子,使用 csv。特别是如果你还没有足够好来调试你的轮子脱落时:)

标签: python file csv


【解决方案1】:

为什么不使用 Python 内置的 csv 模块?

那么,self.derive_pkeys(value) 做了什么?难道b_pkey有时会以\n结尾?

【讨论】:

    【解决方案2】:

    (1) 请准确说明什么是“空白行”——只包含换行符?包含一个或多个空格?其他空白字符?

    (2) 您如何确定 Q1 的答案? [“在文本编辑器中查看”不是一个好的答案,也不是“将其打印到我的终端并注视它”;试试print repr(line)]

    (3) 您是如何确定“缺失数据”实际上在输入字典中的?

    (4) 有些运行有效,有些则无效...那么还有什么不同?字典是从什么填充的?多用户数据库?静态文件?

    【讨论】:

      【解决方案3】:

      在没有看到源数据的情况下很难分辨,但我可以推测您的数据中有一些杂散的 \n 字符,例如 b_pkey 。您可以尝试对该值执行 .strip() 以确保它是干净的。

      【讨论】:

        猜你喜欢
        • 2022-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-31
        • 1970-01-01
        • 2021-09-28
        • 1970-01-01
        相关资源
        最近更新 更多