I have a complex file that is the output of a program. The file contains multiple columns with data in different number formats. For example:


I want to import the data using Import[]. The problem is that Mathematica "reads" the numbers and converts them into objects with Real[] header. As I want to change only a column and the export the file into the same format, I want to be able to access the columns and leave the format unchanged, then update the desired column and export a file into the same format.

I think if there is a form to tell Mathematica that the numbers should be read as Strings will solve the problem.

Some ideas?

  • $\begingroup$ you can always Import[file,"Text"] , then do what you want with string operations. $\endgroup$ – george2079 Apr 8 '15 at 18:15
  • $\begingroup$ No, because i want the structure to be preserved. For example, I want that a table of 3 numbers imported as {"1","2","3"} instead of {"1 2 3"}. $\endgroup$ – Dargor Apr 8 '15 at 18:30
  • $\begingroup$ One you have "1 2 3" use StringSplit to get {"1","2","3"}. Your import might look something like this: StringSplit /@ StringSplit[ Import[file, "Text"] , "\n"] $\endgroup$ – george2079 Apr 8 '15 at 18:43
  • $\begingroup$ Yup, that's perfect! Post that as an answer and i can set this question as answered. :) Thanks! $\endgroup$ – Dargor Apr 8 '15 at 18:49

Example file:


enter image description here

Import as all strings breaking each line into lists, assuming space delimited:

 stringform = 
       StringSplit /@ StringSplit[ Import["test.dat", "Text"] , "\n"];

Here is an example operating on the second column of the result and writing it back out:

 Export["out.dat", StringJoin@Riffle[ 
       (StringJoin@Riffle[#, " "]) & /@ 
          MapAt[ToString[ToExpression[#]/2] &, stringform, {All, 2}] , 
               "\n"], "Text"];

enter image description here

note the columns that we didn't mess with are exactly the same.


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.