2017-01-23 67 views
0

这是一个CSV文件,其中包含多行,但问题是每行包含6个字段,但也有一些字段包含一些缺少fields.So上传结果到数据库时,我想用类似tombsotne替换缺少的字段'NA'。如果csv文件包含空白字段,如何替换虚拟名称?

这里我显示了我写的代码。

with open("results/somename.csv","r") as f: 
     for record in f: 
      #print record.split()[0] 
      record = record.split("|") 
      file1 = record[0] 
      file2 = record[1] 
      file3 = record[2] 
      file4 = record[3] 
      file5 = record[4] 
      if not record[5] : 
       file6 = record[5] 
      else: 
       file6 = 'NA' 
      if not record[6] : 
       file7 = record[6] 
      else: 
       file7 = 'NA' 

在这里,我分割基于所述定界符|该文件,然后试图将文件分割成由于信息记录不足[5]和记录[6]是可以在database.Now被使用的字段在一些行(不是全部)中不可用。因此iam检查它是否包含任何字符串,否则用'NA'替换。但是在执行过程中出现错误。

Traceback (most recent call last): 
    File "db_kiran.py", line 15, in <module> 
    if not record[5] : 
IndexError: list index out of range 

所以我想要在缺失的字段中用'NA'替换。

+1

请检查分割后的数组长度。使用是否执行预期的操作。 –

+0

@SanketSudake谢谢。 –

+0

@ e4c5感谢您的回答,我已经使用了第一条评论并更改了我的代码。 –

回答

1

使用下面的代码

with open("results/somename.csv","r") as f: 
    for record in f: 
     #print record.split()[0] 
     record = record.split("|") 
     file1 = record[0] 
     file2 = record[1] 
     file3 = record[2] 
     file4 = record[3] 
     file5 = record[4] 
     try: 
      file6 = record[5] 
     except IndexError as e: 
      file6 = 'NA' 
      file7 = 'NA' 
      continue 
     try: 
      file7 = record[6] 
     except IndexError as e: 
      file7 = 'NA' 
     'do something' 

希望这有助于!

0

加入到周杰伦对通用的方法代码...

def get_file(record, index, default="N/A"):   
    try: 
     if not record[index]: # not sure above this line, copied from your code 
      return record[index] 
    except IndexError: 
     return default 


with open("results/somename.csv","r") as f: 
     # <your code>... 

     # Posible index error 
     file6 = get_file(record, 5) 
     # Even you can check here 
     # if file6 == 'N/A': 
     # <code to return all next files as N/A> 
     file7 = get_file(record, 6) 
1

很多的东西,努力工作,该数据库由默认原生支持。只需将有问题的列更改为默认值NA即可。这将确保该列显示为NA当你插入一个NULL到它

ALTER TABLE Table1 ALTER COLUMN my_column set DEFAULT 'NA' 

这使得很多代码冗余,但等待,你并不需要通过手动文件迭代和其拆分线按行来做到这一点。 Python对CSV提供了很好的支持,使您的代码可以多行几行。

但等待....

,你可以在一个单一的mysql命令做到这一点。无需Python代码

LOAD DATA INFILE 'somename.csv' INTO TABLE 'Table1' 
FIELDS TERMINATED BY '|' 

LOAD DATA INFILE声明甚至单行以非常高的速度读取文本文件转换成 表行。

相关问题