我想从文件中删除以特定模式开头的所有行。我想用 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/