代码之家  ›  专栏  ›  技术社区  ›  BKCapri

Python3计算CSV中的行数

  •  0
  • BKCapri  · 技术社区  · 6 年前

    从2.7迁移到python3环境后,我在获取行计数时遇到了问题。几次尝试后,返回的行数给出一个。我如何避开一个不推荐使用的警告:python3中不推荐使用“U”模式?

                 input_file = open("test.csv","rU")
                 reader_file = csv.reader(input_file)
                 value = len(list(reader_file))
    

    在使用python3的情况下,我尝试了以下方法,但我仍然坚持使用1。

                 input_file = open("test.csv","rb")
                 reader_file = csv.reader(input_file)
                 value = len(list(reader_file))
    
    0 回复  |  直到 6 年前
        1
  •  4
  •   Vim    6 年前

    如果你使用的是pandas,你可以很容易地做到这一点,而不需要太多的代码。

    import pandas as pd
    
    df = pd.read_csv('filename.csv')
    
    ## Fastest would be using length of index
    
    print("Number of rows ", len(df.index))
    
    ## If you want the column and row count then
    
    row_count, column_count = df.shape
    
    print("Number of rows ", row_count)
    print("Number of columns ", column_count)
    
    
    
        2
  •  0
  •   DYZ    6 年前
    input_file = open("test.csv","rb") #rb is a read-in-binary format and 
    #you can't count the number of row from binary format file
    
    with open("text.csv",'r') as f:
    file = f.readlines()
    print(len(file))
    
    # Data in my text file
    # a
    # b
    # c
    # d
    # e
    
    #The output of above code is 
    #5 means number of rows is 5