Josh
Josh

Reputation: 1337

list.files sometimes adds a slash after the path being searched and sometimes does not add a slash

I am using list.files (or dir) to recursively list the files in a directory on a Windows 10 machine. When I set path = "C:/", the output has a double /. When I set path = "C:" the output has no / after the drive letter.

files_slash <- list.files("C:/", full.names = T, recursive = T, include.dirs = F, no.. = T)
head(files_slash)
[1] "C://$MfeDeepRem/SESSION_COUNT"                                                         
[2] "C://$MfeDeepRem/TERMINATED_SESSIONS/00000001-008e-45fc-8bc2-b49aa3452139/CHANGE_LOG"   
[3] "C://$MfeDeepRem/TERMINATED_SESSIONS/00000001-008e-45fc-8bc2-b49aa3452139/CONFIG_DATA"  
[4] "C://$MfeDeepRem/TERMINATED_SESSIONS/00000001-008e-45fc-8bc2-b49aa3452139/PROCESS_GUIDS"
[5] "C://$MfeDeepRem/TERMINATED_SESSIONS/00000001-01fb-4ff3-9e1f-5c6e94f35645/CHANGE_LOG"   
[6] "C://$MfeDeepRem/TERMINATED_SESSIONS/00000001-01fb-4ff3-9e1f-5c6e94f35645/CONFIG_DATA"  

files_noslash <- dir("C:", full.names = T, recursive = T, include.dirs = F, no.. = T)
head(files_noslash)
[1] "C:$MfeDeepRem/SESSION_COUNT"                                                         
[2] "C:$MfeDeepRem/TERMINATED_SESSIONS/00000001-008e-45fc-8bc2-b49aa3452139/CHANGE_LOG"   
[3] "C:$MfeDeepRem/TERMINATED_SESSIONS/00000001-008e-45fc-8bc2-b49aa3452139/CONFIG_DATA"  
[4] "C:$MfeDeepRem/TERMINATED_SESSIONS/00000001-008e-45fc-8bc2-b49aa3452139/PROCESS_GUIDS"
[5] "C:$MfeDeepRem/TERMINATED_SESSIONS/00000001-01fb-4ff3-9e1f-5c6e94f35645/CHANGE_LOG"   
[6] "C:$MfeDeepRem/TERMINATED_SESSIONS/00000001-01fb-4ff3-9e1f-5c6e94f35645/CONFIG_DATA"  

In response to a question in the comments, the "C:" version (without the /), causes problems, so that is definitely the wrong way to do this:

> file.exists("C://$MfeDeepRem/SESSION_COUNT")
[1] TRUE
> file.exists("C:$MfeDeepRem/SESSION_COUNT")
[1] FALSE

I can use sub to fix the double //, but it doesn't seem like this should not happen. What am I doing wrong? Thanks.

Note, this inconsistency only happens with "C:" (or, I assume, other drive letters). If I give a longer path (e.g. "C:/Users" or "C:/Users/"), a / is always appended to the path.

Upvotes: 0

Views: 436

Answers (1)

Onyambu
Onyambu

Reputation: 79288

Your paths are fine. Don't worry about the extra forwardslash. just normalize them. This will ensure they all look the same.

ie

files_slash <- list.files("C:/", full.names = T, recursive = T, include.dirs = F, no.. = T)
final_files_path <- normalizePath(files_slash)

Upvotes: 3

Related Questions