drkirkby
(David Kirkby)
May 14, 2021, 9:05pm
1
I can create a table of the squares of integers like this
In[1]:= t = Table[{i, i^2}, {i, 10}]
Out[1]= {{1, 1}, {2, 4}, {3, 9}, {4, 16}, {5, 25}, {6, 36}, {7,
49}, {8, 64}, {9, 81}, {10, 100}}
I want to write it to a text file, so the data looks like this
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
I would have thought “Export” could do this, but I could not find the right format Eventually I used “sed” on a Linux system to remove the braces and commas that I got when I exported the data to a file.
I have no doubt there are better ways of doing this, but I think the following will give you what you want.
Export["text1.txt",
StringJoin[ToString[#[[1]]], "\t", ToString[#[[2]]], "\r"] & /@
t, "Text"]
It will create a text file containing all the number pairs, separated by a tab, and with each line ended by a return.
danl
(Daniel Lichtblau)
May 14, 2021, 10:30pm
3
This will work.
StringReplace[ExportString[t, "CSV"], "," -> " "]
Possibly there is an option setting that will obviate the need for StringReplace. Alternatively, use "TSV" as the format.
drkirkby
(David Kirkby)
May 15, 2021, 12:28am
4
Thank you. Since I want a space, not a tab, it suites my needs if I replace the “\t” with " ". I was hoping there would be a simpler way.
scheren
(Sean Cheren)
May 15, 2021, 12:32am
5
Check ref/format/Table for more options but FieldSeparators is what you’re looking for:
Export["test.txt", t, "Table", "FieldSeparators" -> " "]
Another way
Export["t.txt", t, "Table", "FieldSeparators" -> " "]
drkirkby
(David Kirkby)
May 15, 2021, 12:44am
7
Daniel,
Thank you for the reply. However, I’m totally lost on how to apply this when exporting a file - there’s no filename in your code.
drkirkby
(David Kirkby)
May 15, 2021, 12:48am
8
Thank you. That works, and the meaning is quite clear.
drkirkby
(David Kirkby)
May 15, 2021, 12:49am
9
Thank you. That’s essentially the same as Sean’s. I assume your posts overlapped, as they were posted within a few minutes of each other. .