3
$\begingroup$

I have a list of numbers separated by semicolon in text file and I would like to import the data and work with them. If I use

data = ReadList["file",Word,WordSeparators -> ";"] /. Word -> Number

it gives me word or string instead of number. What can I do?

$\endgroup$
3
  • $\begingroup$ ToExpression@ ReadList["file",Word,WordSeparators -> ";"] ? $\endgroup$
    – kglr
    Jun 1, 2017 at 21:26
  • 3
    $\begingroup$ or ReadList["file", "Number", "RecordSeparators" -> {";"}]? $\endgroup$
    – kglr
    Jun 1, 2017 at 21:30
  • $\begingroup$ ImportString[ StringReplace[Import[ file , "Text"] , ";" -> ","] , "CSV"] maybe. (also caution ToExpression wont work if any of the numbers are in E exponent form ) $\endgroup$
    – george2079
    Jun 1, 2017 at 22:08

2 Answers 2

3
$\begingroup$
file = StringToStream["1;2;3;4.5;5.5;6.5"];
ReadList[file, Number, RecordSeparators -> {";"}]

{1, 2, 3, 4.5, 5.5, 6.5}

$\endgroup$
0
$\begingroup$

Your data file (like mine) probably has multiple lines, so using RecordSeparators -> {";"} will destroy the structure. ToExpression is slow but more forgiving (e.g. allows trailing spaces). Using Import is also very slow.

As you typically know the format of your data you can ReadList and call out the format treating the semicolon as a character:

file = StringToStream["1.1;+2;\n3;-4;\n5.5;   6;"];
ReadList[file, {Number, Character, Number, Character}][[;; , ;; ;; 2]]

{{1.1, 2}, {3, -4}, {5.5, 6}}

If you have n columns you may want to use

Flatten@Table[{Number, Character}, n]

or equally

Table[Unevaluated@Sequence[Number, Character], n]
$\endgroup$

Your Answer

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

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