1

I have a number of .csv files that have a semicolon (;) delimiter rather than comma, and I'm wondering if there is a simple way to change the text in them all.

Lets say I have a test file "a.csv" with text:

1;0.5;7
2;0.4;8
3;0.6;7

And I want to convert the semicolons to commas, such that it can import nicely as a csv file.

Test = "1;0.5;7
2;0.4;8
3;0.6;7"
Export["a.csv", Test](*Creates Test File*)

Export["a.csv", ToExpression[ StringReplace[Import["a.csv", "String"], {";" -> ",", "\r\n" -> "\n"}]]](Imports/Replaces/Exports)

FullForm@Import["a.csv", "CSV"](Read Output)

Running the above code results in:

List[List["1,0.5,7\n2,0.4,8\n3,0.6,7"]]

Which is wrong and I'm looking for something that would make:

List[List[1,0.5`,7],List[2,0.4`,8],List[3,0.6`,7]]

The above code works if I am dealing with .txt files, but doesn't seem to function with .csv files. However, I hope to keep the .csv tag in the file names. Is there something I'm missing, or some simpler method?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
ChaSta
  • 1,085
  • 5
  • 15

1 Answers1

2

Use the "Table" format with a custom "FieldSeparators" option:

ImportString["1;0.5;7 2;0.4;8 3;0.6;7", "Table", "FieldSeparators" -> ";"]

You can specify multiple field separators so, as you mentioned in comments, you can also use "FieldSeparators" -> {";", ","} if some of the fields are still comma-separated.

MarcoB
  • 67,153
  • 18
  • 91
  • 189