Search code examples
pythonpandascell

Python read csv single specific cell


Im trying to read just a single cell, in order to bring in the date to use elsewhere. Using pandas I get an error If I try to do this, generally just that the dataframe cant be read because it expects a workable dataframe and not a single cell value prior to the actual convertable dataframe far below the initial line. How can I just get the cell i.e. [A2]

CSV example


Solution

  • Yes, pandas is not very good at files with inconsistent format (like varying number of columns). For that purpose, I recommend you should use csv the standard library.

    The code below should give you the desired value.

    import csv
    
    row = 2; col = 1  # A2 = (2,1) cell
    with open("yourfile.csv") as f:
        reader = csv.reader(f)
        for i in range(row):
            row = next(reader)
        value = row[col-1]  # because python index starts at zero
    print(value)
    

    Demo (using string instead of a file):

    import csv
    
    row = 2; col = 1  # A2 = (2,1) cell
    input_str = ["a,b", "c,d,e", "f,g,h,i"]
    
    reader = csv.reader(input_str)
    for i in range(row):
        row = next(reader)
    value = row[col-1]  # because python index starts at zero
    print(value)