我假设您不只是想读取文件,而是实际修改文件以使其包含列标题。
为了使以下代码工作,您需要定义两个变量:path 应该指向存储原始文件的文件夹。 out_path 应该是文件夹的路径,修改后的文件应该存储在其中。如果文件夹out_path 不存在,则会创建它。
这段代码读取path中的所有csv文件,添加header并将修改后的文件写入文件夹out_path:
# create the output folder
# showWarnings = FALSE ensures that the function does not complain,
# even if the folder already exists
dir.create(out_path, showWarnings = FALSE)
# get the names of the input files with their full path
files <- list.files(path, "\\.csv", full.name = TRUE)
# loop through all the input files
for (file in files) {
# read the file, specify the correct separator
data <- read.table(file, sep = "|")
# set the column names
names(data) <- c("date", "level")
# define the output file name: the file should be written to
# out_path and have the same name as the original file
outfile <- file.path(out_path, basename(file))
# write the file. You need to specify the separator (|), and
# omit row names and quotes
write.table(data, outfile, sep = "|", row.names = FALSE, quote = FALSE)
}
您问题中的示例文件将变成:
date|level
09/21/1299 |23
09/22/1999 |25
09/23/1999 |25
请注意,标题没有很好地对齐。如果文件被读取为 csv 文件,这应该不是问题。