Copy files from few directories - r

I am trying to create a code which copies all folders/files from an existing folder to another (the origin folder has files and more folders that contains files/folders...)
My idea was to do something like this:
files <- list.files (Dir.origen)
for (i in files)
{
if (!file.info (paste(Dir.origen, i, sep = "/"))$isdir)
file.copy (paste(Dir.origen, i, sep = "/"), Dir.dest)
else dir.create (paste(Dir.dest,i,sep = "/"))
}
and insert the same for loop in else statement, and more loops inside.
My question is if there is a way to copy an entire directory.
I am also interested in source this code every time I create a new project in RStudio.
As RStudio creates a new directory for an empty project my objective is to fill this directory with all content I need.

I found out an answer, it is easier then it seems:
Dir.origen2 <- gsub("/","\\\\", Dir.origen) # Directiories must use backslashes
Dir.dest2 <- gsub("/","\\\\", Dir.dest)
comando <- paste0 ("xcopy ", Dir.origen2, " ", Dir.dest2, " /e /i /y")
system(comando)
where /e is for copy all the directories (including empties), /y for don't ask overwriting of documents and /i to create a new directory if Dir.dest do not exists (I guess).

Related

Moving large amounts of files from one large folder to several smaller folders using R

I have over 7,000 .wav files in one folder which need to be split up into groups of 12 and placed into separate smaller folders.
The files correspond to 1-minute recordings taken every 5 minutes, so every 12 files corresponds to 1 hour.
The files are stored on my PC in the working directory: "E:/Audiomoth Files/Winter/Rural/Emma/"
Examples of the file names are as follows:
20210111_000000.wav
20210111_000500.wav
20210111_001000.wav
20210111_001500.wav
20210111_002000.wav
20210111_002500.wav
20210111_003000.wav
20210111_003500.wav
20210111_004000.wav
20210111_004500.wav
20210111_005000.wav
20210111_005500.wav
which would be one hour, then
20210111_010000.wav
20210111_010500.wav
20210111_011000.wav
and so on.
I need the files split into groups of 12 and then I need a new folder to be created in: "E:/Audiomoth Files/Winter/Rural/Emma/Organised Files"
With the new folders named 'Hour 1', 'Hour 2' and so on.
What is the exact code I need to do this?
As is probably very obvious I'm a complete beginner with R so if the answer could be spelt out in layman's terms that would be brilliant.
Thank you in advance
Something like this?
I intentionally used copy instead of cut in order to prevent data from being lost. I edited the answer so the files will keep their old names. I order to give them new names, replace name in the last line by "Part_", i, ".wav", for example.
# get a list of the paths to all the files
old_files <- list.files("E:/Audiomoth Files/Winter/Rural/Emma/", pattern = "\\.wav$", full.names = TRUE)
# create new directory
dir.create("E:/Audiomoth Files/Winter/Rural/Emma/Organised Files")
# start a loop, repeat as often as there are groups of 12 within the list of files
for(i in 1:(round(length(old_files)/12)+1)){
# create a directory for the hour
directory <- paste("E:/Audiomoth Files/Winter/Rural/Emma/Organised Files", "/Hour_", i, sep = "")
dir.create(directory)
# select the files that are to copy (I guess it will start with 1*12-11 = 1st file
# and end with i*12 = 12th file)
filesToCopy <- old_files[(i*12-11):(i*12)]
# for those files run another loop:
for(file in 1:12){
# get the name of the file
name <- basename(filesToCopy[file])
# copy the file to the current directory
file.copy(filesToCopy[file], paste(directory, "/", name, sep = ""))
}
}
When you're not entirely sure, I'd recommend to copy the files instead of moving them directly (which is what I hope this script here does). You can delete them manually, later on. After you checked that everything worked well and all data is where it should be. Otherwise data can be lost due to even small errors, which we do not want to happen.

Delete empty folders inside working directory

I have number of empty folders inside a working directory. Want to remove those empty folders in R. Can somebody help me out on this.
Assuming the current directory is the one in which you want to delete the empty folders, you can do:
folders <- list.dirs(recursive = FALSE)
for(folder in folders){
if(length(dir(folder)) == 0){
unlink(folder, recursive = TRUE)
}
}
We can delete folders using:
unlink("path_to_non_empty_dir", recursive=TRUE)
Edit: removed part about non-empty folders
From ?unlink:
If recursive = FALSE directories are not deleted, not even empty ones.

How to create multiple tempdirs in a single R session?

I need to create multiple temp directories during a single R session but every time I call tempdir() I get the same directory.
Is there an easy way to ensure that every call will give me a new temp directory?
Use dir.create(tempfile()) to create a uniquely named directory inside the R temporary directory. Repeat as necessary.
You can only have one tempdir. But you could create subdirectories in it and use those instead.
If you want to automate the creation of those subdirectories (instead of having to name them manually), you could use:
if(dir.exists(paste0(tempdir(), "/1"))) {
dir.create(paste0(
tempdir(), paste0(
"/", as.character(as.numeric(sub(paste0(
tempdir(), "/"
),
"", tail(list.dirs(tempdir()), 1))) + 1))))
} else {
dir.create(paste0(tempdir(), "/1"))
}
This expression will name the first subdirectory 1 and any subsequent one with increment of 1 (so 2, 3, etc.).
This way you do not have to keep track of how many subdirectories you have already created and you can use this expression in a function, etc.

fread zipped file with 7z

I want to read in a file with fread in R. I have 7z installed.
I tried
fread(shell(cmd = '7z l test.txt.gz'), shell = 'cmd.exe'))
However I get the error
Error in fread(shell(cmd = paste0("7z x ", "\"", dest, "\""), shell = "cmd.exe")) :
'input' must be a single character string containing a file name, a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself
I'm looking for something similar to:
fread(shell(cmd = 'unzip -cq test.zip', shell = 'cmd.exe'))
One work-around is to copy 7z.exe to the project folder. And try:
DT = fread(cmd = '7z e -so "test.zip"')
Some people suggested adding 7-zip to Windows PATH Environment Variable. But it did not work for me.

Applying script in subfolders

I cd into a folder and start python. I want to apply a script to fix filenames in a directory and in sub folders.
import os
for dirname, subdirs, files in os.walk('.'):
os.rename(file, file.replace('\r', '').replace('\n', '').replace(' ', '_')
print 'Processed ' + file.replace('\r', '').replace('\n', '')
I get error "AttributeError: 'list" object has no attribute 'replace'. Help, please?
os.walk returns a 3-tuple that includes the root directory of the script, a list of subdirectories, and a list of files. You unpacked the 3-tuple in the for-loop and you're calling replace on the list of files.
You may want something like this:
for dirname, subdirs, files in os.walk('.'):
for file in files:
os.rename(file, file.replace('\r', '').replace('\n', '').replace(' ', '_')
print 'Processed ' + file.replace('\r', '').replace('\n', '')
You want to iterate through the list of the files and do you "replacing" on those individual files.

Resources