如何根据数字移动某些文件?

时间:2013-09-20 15:58:26

标签: r

我有一个文本文件包含(head):

"Grid.Point.Index" "Latitude" "Longitude" "Cell"
"544361" 2093507 40.071983 0 1322
"545570" 2098421 40.184559 0 1322
"545571" 2098423 40.184559 0.146776 1322
"546781" 2103327 40.297134 0 1322
"546782" 2103329 40.297134 0.14702 1322
"546784" 2103333 40.297134 0.294039 1322

阅读文件:

table= read.table("C:\\Users\\lonlatnter.txt", sep=",",header=TRUE)

第二列中的每个数字都有另一个文件夹data中的关联文件。 我在这个文件夹中有数千个文件,所谓的"data"

列出文件:

data<- list.files("D:\\data", "*.csv", full.names = TRUE)

文件名称为(示例)data_num_gp2103333.csv

gp之后的名称中的数字对应于文本文件中的第二列。

我想将文本文件第二列中存在数字的文件从文件夹data移动(或复制)到新文件夹mydata。 请帮忙。

str( table )

'data.frame':   374 obs. of  4 variables:
$ Grid.Point.Index: int  2093507 2098421 2098423 2103327 2103329 2103333 2108225 2108227 
                         2108231 2113115 ...
$ Latitude        : num  40.1 40.2 40.2 40.3 40.3 ...
$ Longitude       : num  0 0 0.147 0 0.147 ...
$ Cell            : int  1322 1322 1322 1322 1322 1322 1322 1322 1322 1322 ...

1 个答案:

答案 0 :(得分:2)

您可以尝试以下示例。首先,我们遍历Index中的每个table值(旁注 - 有一个名为table()的函数,所以我要避免调用变量this)。我们列出包含此索引值的文件。我假设每个索引值与单个文件有关。既然如此,我们返回文件名的字符向量。

接下来,我们遍历文件名,将每个文件复制到文件夹"D:/NewData"(驱动器上必须已存在)。该文件将具有原始文件名,只在新文件夹中。我为此使用了for循环,因为a)循环的执行时间与执行file.copy和b)所需的时间相比可以忽略不计,因为我们为它调用了file.copy -effect(从/向指定位置复制文件)而不是它的返回值(指示副本是否成功的逻辑)。

fls <- sapply( table[,2] , function(x) list.files( path = "D:\\data"  , pattern = as.character( x ) , full.names = TRUE ) )

#  Use a 'for' loop here because we are calling the
#  file.copy function for it's side effect rather
#  than return value (i.e. to copy a file)
for( i in fls ){
    file.copy( from = i , to = paste0( "D:/NewData/" , basename( i ) ) )
}