0

I have a list of numbers:

e.g. list={1,2,3,4,5}

To write the list to a file I use (here each integer number occupies 7 spaces):

WriteString[file, 
  Row[{Row[PaddedForm[#, 7] & /@ list, " "], "\n"}]];

(I took the proposal from: How can write a list as a formatted string to a file)

Is there also another solution to do that?

mrz
  • 11,686
  • 2
  • 25
  • 81

2 Answers2

2

Here's how I would do it with PaddedForm:

Export["filepath.txt", 
 StringJoin[ToString@PaddedForm[#, 6] & /@ {-1, 2, 3, 4, 5}]]

This works with negative numbers as well. Will work the same with WriteString.

If you want more control over the padding, you can use your own function...

custompad[num_, padlength_?IntegerQ] := StringPadLeft[ToString@num,padlength]
SetAttributes[custompad, Listable]


str = OpenWrite[]
WriteString[str, StringJoin@custompad[RandomInteger[{-100, 100}, 20], 7]]
Close[str]

FilePrint[%]

-17 -35 -38 -64 88 34 23 -100 2 55 84 -11 -46 -87 -46 -86 -53 35 -6 -50

kale
  • 10,922
  • 1
  • 32
  • 69
2

I don't know if this is what you are after, but this is how I always import / export long lists:

Export

Export["C:\\Directory\\list.txt", list]

Import

list = ToExpression[Import["C:\\Directory\\list.txt", "List"]];
martin
  • 8,678
  • 4
  • 23
  • 70