0
$\begingroup$

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?

$\endgroup$
0
2
$\begingroup$

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

$\endgroup$
2
$\begingroup$

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"]];
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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