Python: How to check if cell in CSV file is empty?

后端 未结 6 1302
天命终不由人
天命终不由人 2020-12-17 02:40

I have a CSV file that I\'m reading in Python and I want the program to skip over the row if the first column is empty. How do I do this?

Right now I have:



        
相关标签:
6条回答
  • 2020-12-17 02:52

    I tried out what happens if you print and empty row and it returns [] (empty brackets)... so just check for that.

    with open('testdata1.csv', 'rU') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            if row == []:
                continue
            #do stuff normally
       
    
    0 讨论(0)
  • 2020-12-17 02:56

    You could use try and except.

    for row in csvreader:
            try:
                   #your code for cells which aren't empty
            except:
                   #your code for empty cells
    
    0 讨论(0)
  • 2020-12-17 03:02

    I would assume if you len() it then would be zero i.e.

    if not len(row[0])
    
    0 讨论(0)
  • 2020-12-17 03:03

    Small adaptation of Kit Fung's answer:

    with open('testdata1.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        if not row[0]:
             continue  # this will skip to the next for loop iteration
        # do your processing here
    
    0 讨论(0)
  • 2020-12-17 03:07

    After hour of trying I was able to do it

    while act_tab.cell(row=i, column=1).value is not None:
        ...
    
    0 讨论(0)
  • 2020-12-17 03:17
    with open('testdata1.csv', 'r') as csvfile:
        csvreader = csv.reader(csvfile)
        for row in csvreader:
            print(row)
            if row[0] in (None, ""):
                 print("12")
    

    Reference: How do I detect missing fields in a CSV file in a Pythonic way?

    0 讨论(0)
提交回复
热议问题