import numpy as np
a=np.array([1,2,3,4,5,6,7,8,9,10])
n=int(input("Enter the number of splits : "))
for i in range(n):
aa=a[np.arange(i, len(a), n)]
name="file" str(i 1) ".txt"
with open(name,'w') as f:
for values in aa:
f.write(str(values))
f.write('\t')
o/p:
Enter the number of splits : 3
array[[1,4,7,10],[2,5,8],[3,6,9]]
Here I have splitted the array into three and for each splitting the separate files are created namely
`
file1.txt` which has [1,4,7,10]
`file2.txt` which has [2,5,8]
`file3.txt` which has [3,6,9]
In this code ,I have used for loop and iterate over the each split value by value and then write the elements into the respective file. And the one element must be placed one tab space from another element.
name="file" str(i 1) ".txt"
with open(name,'w') as f:
for values in aa:
f.write(str(values))
f.write('\t')
How to write to the file once instead of writing one number and tab at a time.
CodePudding user response:
You can use f-string
.
In evaluation str
function is called automatically on the object.
name="file" str(i 1) ".txt"
with open(name,'w') as f:
for values in aa:
f.write(f'{values}\t'))