1
$\begingroup$

Hopefully a simple one for you (or at least seemingly)!

I import a .txt file, from which i make a ListLinePlot. I simply want to read in the name of the file, store it in a variable so I can use it to tag my plots later.

    Data = Import["C:\\Users\\Name\\Folder\\test2.txt", "CSV"];
ListLinePlot[Transpose[{Data[[All, 1]], Data[[All, 2]]}], 
 Frame -> True, 
 PlotRange -> {{Data[[All, 1]][[
      First@Flatten[Position[Data, {_, Max[Data[[All, 2]]]}]]]]
      - 0.0003, 
    Data[[All, 1]][[
      First@Flatten[Position[Data, {_, Max[Data[[All, 2]]]}]]]]
     + 0.0003}}, FrameTicks -> Automatic, Axes -> False, 
 PlotStyle -> Directive[Black, Thin], 
 FrameLabel -> {"SIMULATION TIME STEP [\[Mu]s]", 
   "PARTICLE NUMBER [#]"}]

Here is my code I'm using to plot, the filename is "test2", and it is that I would like to extract.

Thanks in advance,

QP

$\endgroup$

2 Answers 2

6
$\begingroup$

I don't know if I understand you correctly. but here is what I got for you:

FileNameTake["C:\\Users\\Name\\Folder\\test2.txt"]
(*"test2.txt"*)

If you want without extension, then:

FileBaseName["C:\\Users\\Name\\Folder\\test2.txt"]
(*test2*)
$\endgroup$
2
$\begingroup$

Given you already have the filename as a text string you could specify the file name and path separately when you first run, and create the full path & filename using FileNameJoin. FileNameJoin is OS agnostic so puts in forward or backslashes depending on whether you are running Windows, OSX or Linux.

Alternatively if you want something a bit more dynamic you can use Algohi's solution after first getting the filename with either

file = SystemDialogInput["FileOpen"]
(* Brings up a standard FileOpen dialog box specific to your OS *)

FileNameSetter[Dynamic[file2], "Open"]

(*  Creates a browse button in your notebook which opens a 
file open dialog box when clicked and file2 is set when 
you click on a file *)

For both options you can limit the shown files to a particular filename extension such as CSV.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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