是否可以获取CSV文件中的行数而不打开它?

我有一个大小约为1 GB的CSV文件,由于我的笔记本电脑是基本configuration的,我无法在Excel或R中打开文件。但出于好奇,我想获得行数文件。 我该怎么做,如果有的话,我可以做到。 提前致谢。

对于Linux / Unix:

 wc -l filename 

对于Windows:

 find /c /v "A String that is extremely unlikely to occur" filename 

不确定其效率,但这里有一个基本的R方法。 通过文件连接, count.fields()计算文件每行的字段数。 所以,如果我们取得结果的长度,理论上应该以文件中的行数(行)结束。

 length(count.fields(filename)) 

如果你有一个标题行,你可以跳过它skip = 1

 length(count.fields(filename, skip = 1)) 

还有其他的参数可以根据您的具体需求进行调整。

 args(count.fields) # function (file, sep = "", quote = "\"'", skip = 0, blank.lines.skip = TRUE, # comment.char = "#") # NULL 

有关更多信息,请参阅help(count.fields)

更新:速度还不算太差。 我只testing了一个包含99846行的棒球文件。

 nrow(data.table::fread("Batting.csv")) # [1] 99846 system.time({ l <- length(count.fields("Batting.csv", skip = 1)) }) # user system elapsed # 0.528 0.000 0.503 l # [1] 99846 file.info("Batting.csv")$size # [1] 6153740 

另一个想法是使用data.table::fread()只读取第一列,然后取行数。 这将是非常快的。

 system.time(nrow(fread("Batting.csv", select = 1L))) # user system elapsed # 0.063 0.000 0.063 

这是我用过的东西:

 testcon <- file("xyzfile.csv",open="r") readsizeof <- 20000 nooflines <- 0 ( while((linesread <- length(readLines(testcon,readsizeof))) > 0 ) nooflines <- nooflines+linesread ) close(testcon) nooflines 

看看这个post了解更多: https : //www.r-bloggers.com/easy-way-of-determining-number-of-linesrecords-in-a-given-large-file-using-r/