how to skip blank line while reading CSV file using python

后端 未结 8 601
终归单人心
终归单人心 2020-12-03 20:55

This is my code i am able to print each line but when blank line appears it prints ; because of CSV file format, so i want to skip when blank line appears

im         


        
相关标签:
8条回答
  • 2020-12-03 21:28
    import csv
    
    with open('userlist.csv') as f:
    
        reader = csv.reader(f)
        user_header = next(reader)       # Add this line if there the header is
    
        user_list = []                   # Create a  new user list for input
        for row in reader:
            if any(row):                 # Pick up the non-blank row of list
                print (row)              # Just for verification
                user_list.append(row)    # Compose all the rest data into the list
    
    0 讨论(0)
  • 2020-12-03 21:30

    my suggestion would be to just use the csv reader who can delimite the file into rows. Like this you can just check whether the row is empty and if so just continue.

    import csv
    
    with open('some.csv', 'r') as csvfile:
    
        # the delimiter depends on how your CSV seperates values
        csvReader = csv.reader(csvfile, delimiter = '\t')
    
        for row in csvReader:
            # check if row is empty
            if not (row):    
                continue
    
    0 讨论(0)
  • 2020-12-03 21:32

    Instead of

    if not line:
    

    This should work:

    if not ''.join(line).strip():
    
    0 讨论(0)
  • 2020-12-03 21:34
    import csv
    ifile=csv.reader(open('C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv', 'rb'),delimiter=';')
    for line in ifile:
        if set(line).pop()=='':
            pass
        else:
            for cell_value in line:
                print cell_value
    
    0 讨论(0)
  • 2020-12-03 21:43

    You can always check for the number of comma separated values. It seems to be much more productive and efficient.

    When reading the lines iteratively, as these are a list of comma separated values you would be getting a list object. So if there is no element (blank link), then we can make it skip.

            with open(filename) as csv_file:
              csv_reader = csv.reader(csv_file, delimiter=",")
              for row in csv_reader:
                if len(row) == 0:
                    continue
    
    0 讨论(0)
  • 2020-12-03 21:44

    You can strip leading and trailing whitespace, and if the length is zero after that the line is empty.

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