2010-06-04 45 views
0

我有一段代碼運行一個字典,並以CSV格式輸出它的值。奇怪的是,我得到了幾行空白行,其中所有字典條目的輸出都是空白的。我讀過代碼,不能理解除了逗號可以輸出的行外。空白行應該包含值,所以\ n不是原因。任何人都可以建議我爲什麼會空白行嗎?其他時候我運行失蹤線出現。python輸出中意外的空行

缺失行:

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 
+0

首先學會使用內置的字符串格式化函數,http://docs.python.org/library/stdtypes.html#string-formatting – 2010-06-04 05:59:00

+2

@fuzzy:這些都在Python 3.0中消失了,無論如何,我會說迭代風格;-) Martlark,這是'對於recrange_a在xrange(max_rec_num_a)'' – 2010-06-04 06:17:22

+0

''我使用字符串格式錯誤?我沒有使用內置的csv模塊,因爲這不是我的代碼。 – Martlark 2010-06-04 06:21:41

回答

3

你爲什麼不使用Python的內置 - 在csv模塊?

那麼,self.derive_pkeys(value)做什麼?難道b_pkey有時會以\n結束?

1

沒有看到源數據很難說,但我可以推測你的數據有一些流浪\n字符在裏面,就像在b_pkey。您可以嘗試在該值上執行.strip()以確保它是乾淨的。

+4

這將是'.strip()' – 2010-06-04 06:22:39

1

(1)請準確地說出「空白行」是什麼 - 僅包含換行符?包含一個或多個空格?其他空白字符?

(2)您是如何確定Q1的答案的? [「在文本編輯器中查看」不是一個好的答案,也不是「將它打印到我的終端並使其眼睛」;請嘗試print repr(line)]

(3)您如何確定「缺失數據」實際上是在輸入字典中?

(4)一些運行工作,一些不運行...所以還有什麼不同?從什麼是字典填充?多用戶數據庫?一個靜態文件?