我尝试在Windows 7 / R 3.2.2 x64下将字符向量写入文本文件,我想要unix LF - 而不是Windows CRLF:
v <- c("a","b","c")
cat(nl,file="textfile.txt",sep="\n")
写入
> a[CRLF]
> b[CRLF]
> c[CRLF]
cat(paste(nl,sep="\n",collapse="\n"),file="t2.txt")
写入
> a[CRLF]
> b[CRLF]
> c
我也尝试过write.table(eol =“\ n”) - 因为它似乎在内部使用cat而失败。
我寻找其他解决方法; 我试图找到某事。在R \ src \ main \ scan.c中,找到第387ff行的相关代码。
任何知道我如何在输出文件中获得类似UNIX的LF的人?
答案 0 :(得分:2)
尝试以“二进制”模式(而不是“文本”模式)打开文件连接,以防止对行尾的系统相关编码:
import itertools
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return itertools.izip_longest(fillvalue=fillvalue, *args)
def chunkreader(f, n):
chunks = grouper(f, n, "")
for chunk in chunks:
yield(line.strip() for line in chunk)
def process(chunk):
d = {}
for line in chunk:
if line:
k, v = line.split(":")
d[k] = v
insert_in_db(d)
def insert_in_db(d):
# mock
print d
with open("test.txt") as f:
for chunk in chunkreader(f, 12):
process(chunk)
答案 1 :(得分:0)
基于@xb的答案
converter <- function(infile){
print(infile)
txt <- readLines(infile)
f <- file(infile, open="wb")
cat(txt, file=f, sep="\n")
close(f)
}