繁体   English   中英

Django python escape \\ n字符

[英]Django python escape \n characters

在下面的函数中,我从模板上传文件并将其传递给以下函数。但是如果有\\ n或\\ t( This is a tab separated file ),数据就会被削弱。

1.如果有一个\\ n或一些特殊字符,它会将数据存储在下一行。如何避免这种情况。

2.data不是None或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. 使用stdlib的csv模块来解析你的文本,它会更好。

  2. 您的表达式data is not None or data != ""始终为true,您的意思是data is not None and data != "" 请注意,您可以将此简化为elif counter == 3 and data:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM