2012-07-24 63 views
0

在以下函數中,我從模板上傳文件並將其傳遞給以下函數。但是如果存在\ n或\ t(This is a tab separated file),則數據會受到損壞。Django python轉義字符

1.如果有\ n或某些特殊字符,它會將數據存儲在下一行。如何避免這種情況。

2.data不無或數據!=「」仍然保存空值

def save_csv(csv_file,cnt): 
ret = 1 
arr = [] 
try: 
    flag = 0 
    f = open(csv_file) 
    for l in f: 
    if flag == 0: 
     flag += 1 
     continue 
    parts = l.split("\t") 
    counter = 1 
    if(len(parts) > 6): 
     ret = 2 
    else: 
     taggeddata = Taggeddata() 
     for data in parts: 
      data = str(data.strip()) 
      if counter == 1 and (data is not None or data != ""): 
       taggeddata.field1 = data 
      elif counter == 2 and (data is not None or data != ""): 
       taggeddata.field2 = data 
      elif counter == 3 and (data is not None or data != ""): 
       taggeddata.field3 = data 
      elif counter == 4 and (data is not None or data != ""): 
       taggeddata.field4 = data 
      elif counter == 5 and (data is not None or data != ""): 
       taggeddata.field5 = data 
      elif counter == 6 and (data is not None or data != ""): 
       taggeddata.field6 = data 
      counter += 1 
     taggeddata.content_id = cnt.id 
     taggeddata.save() 
     arr.append(taggeddata) 
    return ret 
except: 
    write_exception("Error while processing data and storing") 
+1

不推倒重來,使用[CSV模塊(http://docs.python.org/library/csv.html)來處理CSV文件,該模塊能夠處理正確的轉義和其他問題。 – 2012-07-24 11:19:30

回答

2
  1. 使用STDLIB的CSV模塊來解析文本,這將是它好得多。

  2. 你的表情data is not None or data != ""永遠是真的,你的意思是data is not None and data != ""。請注意,您可以簡化這只是elif counter == 3 and data: