r - 如何同时逐行读取和写入文件?

标签 r connection readlines

我想从文件中删除以特定模式开头的所有行。我想用 R 来做到这一点。最好不要先读取整个文件,然后删除所有匹配的行,然后再写入整个文件,因为文件可能很大。因此,我想知道是否可以对同一个文件同时具有读取和写入连接(始终打开,一次一个?)。下面显示了这个想法(但“挂起”,因此失败)。

## Create an example file
fnm <- "foo.txt" # file name
sink(fnm)
cat("Hello\n## ----\nworld\n")
sink()

## Read the file 'fnm' one line at a time and write it back to 'fnm'
## if it does *not* contain the pattern 'pat'
pat <- "## ----" # pattern
while(TRUE) {
    rcon <- file(fnm, "r") # read connection
    line <- readLines(rcon, n = 1) # read one line
    close(rcon)
    if(length(line) == 0) { # end of file
        break
    } else {
        if(!grepl(pat, line)) {
            wcon <- file(fnm, "w")
            writeLines(line, con = wcon)
            close(wcon)
        }
    }
}

注意:

1) 请参阅here如果有人写入新文件,则会得到答案。然后,我们可以删除旧文件并将新文件重命名为旧文件,但这看起来不太优雅:-)。

2) 更新:以下 MWE 产生

Hello
world
-
world

参见:

## Create an example file
fnm <- "foo.txt" # file name
sink(fnm)
cat("Hello\n## ----\nworld\n")
sink()

## Read the file 'fnm' one line at a time and write it back to 'fnm'
## if it does *not* contain the pattern 'pat'
pat <- "## ----" # pattern
con <- file(fnm, "r+") # read and write connection
while(TRUE) {
    line <- readLines(con, n = 1L) # read one line
    if(length(line) == 0) break # end of file
    if(!grepl(pat, line))
        writeLines(line, con = con)
}
close(con)

最佳答案

我认为你只需要open = 'r+'。来自?文件:

Modes

"r+", "r+b" -- Open for reading and writing.

我没有您的示例文件,因此我只提供以下最小示例:

取一个 26 行包含 a-z 的文件,并将其逐一替换为 A-Z:

tmp = tempfile()
writeLines(letters, tmp)
f = file(tmp, 'r+')
while (TRUE) {
  l = readLines(f, n = 1L)
  if (!length(l)) break
  writeLines(LETTERS[match(l, letters)], f)
}
close(f)

readLines(f) 随后确认此操作有效。

关于r - 如何同时逐行读取和写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54798340/

相关文章:

windows - 将端口 21 更改为 30 后,FileZilla FTP 服务器错误 "425 Can' t 打开数据连接

python - 在 Python 中打印多个文件的特定行

Python 使用名称和分数对文件进行排序

r - 如何在数据框中找到最大值?

r - ggplot2使用运行变量设置geom_text标签

r - 在 R 中创建新的数据框

r - 如何根据分隔符之前的值对 R 中的向量元素进行排序

java - 10 分钟后连接重置 java

java - 连接对象的单例实例是否会在 Web 应用程序中产生问题

html - 使用 R 从 html 页面中提取数据