【问题标题】:How to open a file and then write lines to it in a loop如何打开文件然后循环写入行
【发布时间】:2019-11-18 13:22:06
【问题描述】:

有很多具有类似主题的 R 帖子,但它们没有提供我正在寻找的内容。

我想要的伪代码(这不是R)如下:

fileConn <- file("foo.txt")
for (i in 1:hiLimit) {
  # extract elements from each nested and variable json element in an R list.
  # paste elements into a comma separated list
  write(pastedStuff,fileConn)
}
close(fileConn)

现在,如果我跳过“文件”和“关闭”,而只使用带有文件名和“附加=真”的“猫”,如下所示:

cat(paste(cve,vndr,pnm,vnmbr,vaffct,sep=","),file="outfile.txt",append=TRUE,sep="\n")

我得到了我想要的。但是,据推测,这是为每个调用打开和关闭文件(??? 假设)。避免这种情况应该会使其更快。

我无法解决的是如何通过伪代码中的方法实现结果,该方法仅打开和关闭文件一次。使用 'cat' 或 'writeLines' 只会给我文件中的最后一行。

作为解释,我正在处理的问题涉及从头开始逐行构建数据框。我的时间安排(见下文)表明,到目前为止,我能做到这一点的最快方法是将 csv 写入磁盘,然后将其读回以创建数据帧。这很疯狂,但这就是它的发展方式。

## Just the loop without any attempt to collect parsed data into a dataframe
system.time(tmp <- affectsDetails(CVEbase,Affect))
   user  system elapsed 
   0.30    0.00    0.29 

## Using rbind as in rslt<- rbind (rslt,c(stuff)) to build dataframe in the loop.
system.time(tmp <- affectsDetails(CVEbase,Affect))
   user  system elapsed 
 990.46    2.94  994.01 

# Preallocate and insert list as per 
# https://stackoverflow.com/questions/3642535/creating-an-r-dataframe-row-by-row
system.time(tmp <- affectsDetails(CVEbase,Affect))
   user  system elapsed 
1451.42    0.04 1452.37 

# Write to a file with cat and read back the csv.
system.time(tmp <- affectsDetails(CVEbase,Affect))
   user  system elapsed 
  10.70   29.00   45.42

任何建议表示赞赏!

【问题讨论】:

    标签: r file


    【解决方案1】:

    不确定我可以如何帮助您。但是您可以打开一个连接并保持打开状态直到写入完成。

    testcon <- file(description = "C:/test.txt", open = "a")
    
    isOpen(testcon)
    [1] TRUE
    
    start <- Sys.time()
    for (i in 1:10000) {
    
     cat(paste0("hallo", i), file= testcon, append=TRUE,sep="\n")
    
    }
    end <- Sys.time()
    
    end-start
    Time difference of 0.2017999 secs
    
    close(testcon)
    
    

    这似乎比:

    start <- Sys.time()
    for (i in 1:10000) {
    
      cat(paste0("hallo", i), file= "C:/test.txt", append=TRUE,sep="\n")
    
    }
    end <- Sys.time()
    
    end-start
    Time difference of 3.382569 secs
    

    【讨论】:

    • 这似乎做到了!非常感谢。观察到相同的加速,提高 10 倍。我怀疑是 ' open="a" ' 有所作为。弄清楚为什么内存中的性能如此糟糕将是另一天的问题。
    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多