如何遍历不同目录中的文件 [英] How to loop over files in different directories

查看:77
本文介绍了如何遍历不同目录中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想遍历多个文件并对其应用一个功能.问题在于这些文件都位于不同的但名称相似的目录中.路径模式相似,但数量根据其所属的家庭而变化.

I want to loop over multiple files and apply a function to them. The problem is that these files are all in different, but similarly named, directories. The pathway pattern is similar, but the number changes according to what family it's up to.

例如,我有这样编写的代码:

For example, I have code written as this:

for(i in 1:numfiles) {
    olddata <- read.table(paste("/home/smith/Family", i, "/Family", i, ".txt", sep="\t"),
                          header=T)      
    # FUNCTION GOES HERE

    write.table(newdata,
                paste("/home/smith/Family", i, "/Family", i, "test.txt",
                      sep = ",", quote=F, row.names=F)
}

我的问题是,家庭号码不是按数字顺序排列的.有些标有一个数字(例如:2),而另一些标有字母(例如:1a)

The problem I have is that the family numbers don't go in numeric order. Some are labeled just with a number (ex: 2) and others have a letter appended to that number (ex: 1a)

在每个家庭子目录(即家庭i)中,我想调用相同的文件(文件名完全相同,但数字(i)根据其所指的家庭而改变).我想遍历这些特定文件.例如...对于家庭1a,文件在此处:"/home/smith/Family1a/Family1a.txt",但是对于家庭2,文件在此处:"/home/smith/Family2/Family2.txt".

In each family subdirectory (ie Family i) I want to call in the same file (the file name is exactly the same but with the number (i) changed according to what family it refers to). I want to loop over these particular files. For example... For family 1a the file is here: "/home/smith/Family1a/Family1a.txt" but for family 2 the file is here: "/home/smith/Family2/Family2.txt".

此外,R不喜欢我使用numfiles.

Also, R doesn't like my use of numfiles.

推荐答案

看看?list.files?dir,例如:

files <- list.files("/home/smith", pattern="Family[[:alnum:]]+.txt", recursive=TRUE, full.names=TRUE)

for (currentFile in files) {
  olddata <- read.table(currentFile, header=TRUE)
  ## some code
  write.table(newdata, file=sub(pattern=".txt$", replacement="test.txt", x=currentFile))
}

或者:

dirs <- dir("/home/smith", pattern="Family[[:alnum:]]+$")

fileName <- file.path(dirs, paste0(dirs, ".txt"))
testFileName <- file.path(dirs, paste0(dirs, "_test.txt"))

for (i in seq(along=fileName))

  olddata <- read.table(fileName[i], header=TRUE)
  ## some code
  write.table(newdata, file=testFileName[i])
}

这篇关于如何遍历不同目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆