Message Boards Message Boards

0
|
7925 Views
|
8 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Export numbers in two columns, without braces or commas?

Posted 3 years ago

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.

POSTED BY: David Kirkby
8 Replies
Posted 3 years ago

Another way

Export["t.txt", t, "Table", "FieldSeparators" -> " "]
POSTED BY: Rohit Namjoshi
Posted 3 years ago

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. .

POSTED BY: David Kirkby
Posted 3 years ago

Check ref/format/Table for more options but FieldSeparators is what you're looking for:

Export["test.txt", t, "Table", "FieldSeparators" -> " "]
POSTED BY: Sean Cheren
Posted 3 years ago

Thank you. That works, and the meaning is quite clear.

POSTED BY: David Kirkby

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.

POSTED BY: Daniel Lichtblau
Posted 3 years ago

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.

POSTED BY: David Kirkby
Posted 3 years ago

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.

POSTED BY: Andrew Burnett
Posted 3 years ago

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.

POSTED BY: David Kirkby
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract