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?

  • 1
    $\begingroup$ see documentation for FileNameTake, FileBaseName and FileExtension, DirectoryName might also be of interest... $\endgroup$ – Albert Retey Nov 11 '15 at 8:52
  • $\begingroup$ Why can't you use the full path of the file...? It still points to the file you want to move. $\endgroup$ – Marius Ladegård Meyer Nov 11 '15 at 8:54
  • $\begingroup$ @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. $\endgroup$ – Sjoerd C. de Vries Nov 11 '15 at 9:17

Useful functions in this context:

Split the path in components:

(* {"U", "SomeDirectory", "SomeSecret Directory", "veryImportantFile.pdf"} *)

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

(* "veryImportantFile" *)

Get the name, including the file extension:

(* "veryImportantFile.pdf" *)

Get the extension itself:

(* "pdf" *)

Get the directory only:

(* "U\\SomeDirectory\\SomeSecretDirectory" *)

or by:

(* "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" *)

OS choice made explicitly:

FileNameJoin[{"U", "SomeDirectory", "SomeSecret Directory", "veryImportantFile.pdf"}, 
             OperatingSystem -> #
] & /@ {"Windows", "Unix", "MacOSX"}
(* {"U\\SomeDirectory\\SomeSecretDirectory\\veryImportantFile.pdf",
    "U/SomeDirectory/SomeSecretDirectory/veryImportantFile.pdf"} *)
  • $\begingroup$ Thank you, that's very helpful ! $\endgroup$ – Yossi Lonke Nov 11 '15 at 10:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.