# Moving files around

In order to introduce some order into the chaos, I want to move all pdf files on some big directory, say, "U:\", into a library directory, say: "U:\Library". So I get a list all files situated anywhere within my univerese by:

pdfFiles = FileNames["*.pdf", {"*"}, Infinity];


and now I would like to map CopyFile on pdfFiles so that all files will move to "U:\Library". The problem is that the file-names of pdfFiles all carry their full path name, e.g "U\SomeDirectory\SomeSecretDirectory\veryImportantFile.pdf". Of course, I don't want to copy the entire path. Only the last name "veryImportantFile.pdf".

Is there a quick way to do that, or must I painfully parse out the last names of each one of the files?

• see documentation for FileNameTake, FileBaseName and FileExtension, DirectoryName might also be of interest... Nov 11, 2015 at 8:52
• Why can't you use the full path of the file...? It still points to the file you want to move. Nov 11, 2015 at 8:54
• @MariusLadegårdMeyer becuase the OP wants to use the base filename (without path) to be used as target in a new directory. So, the issue is not the source name, it is the target name. Nov 11, 2015 at 9:17

Useful functions in this context:

Split the path in components:

FileNameSplit["U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf"]
(* {"U", "SomeDirectory", "SomeSecret Directory", "veryImportantFile.pdf"} *)


Get the 'pure' file name (without file extension):

FileBaseName["U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf"]
(* "veryImportantFile" *)


Get the name, including the file extension:

FileNameTake["U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf"]
(* "veryImportantFile.pdf" *)


Get the extension itself:

FileExtension["U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf"]
(* "pdf" *)


Get the directory only:

FileNameDrop["U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf"]
(* "U\\SomeDirectory\\SomeSecretDirectory" *)


or by:

DirectoryName["U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf"]
(* "U\\SomeDirectory\\SomeSecretDirectory\\" *)


[Note the latter includes a final slash, whereas the former doesn't]

The inverse of FileNameSplit is FileNameJoin. It is an important function as it makes sure to use the path separators that work on the OS the user is working on and it makes file paths system independent.

No option (Mathematica automatically chooses OS):

FileNameJoin[{"U", "SomeDirectory", "SomeSecret Directory", "veryImportantFile.pdf"}]
(* "U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf" *)


FileNameJoin[{"U", "SomeDirectory", "SomeSecret Directory", "veryImportantFile.pdf"},