import math
class Vector():
def __init__(self,vx,vy,vz):
self.x=vx
self.y=vy
self.z=vz
def norm(self):
xx=self.x**2
yy=self.y**2
zz=self.z**2
return math.sqrt(xx+yy+zz)
Now in the run file
import math
import numpy as np
from Desktop import Test
def random_range(n, min, max):
return min + np.random.random(n) * (max - min)
x=random_range(20,2,9)
y=random_range(20,2,9)
z=random_range(20,2,9)
trial_args = np.stack((x, y, z), axis=-1)
for x, y, z in trial_args:
model=Test.Vector(x,y,z)
if model.norm()>5:
print(x, y, z, '=>', model.norm())
I want to get each (x,y,z) output in a seperate output file named 1,2,3β¦20 so how to do this job with these codes
Assuming these files run ok, in your loop you can enumerate the args with start=1 and pass that index value into a function, e.g. write_to_file(). Call the function in the loop by passing in a string of values.
Code
def write_to_file(index_name: int, text: str, ext: str=".txt"):
"""Return a filepath and write text to the file."""
filename = str(index_name) + ext
with open(filename, "w") as f:
f.write(text)
return filename
You should see a file with that name in the same directory. See more details on Python I/O from the docs. If you want more control over file paths, consider using pathlib.
βI want to get each (x,y,z) output in a seperate output file named
1,2,3β¦20 so how to do this job with these codesβ
At the top of your script, define a variable:
filenumber = 0
Then in your for-loop:
if model.norm() > 5:
filenumber += 1
filename = str(filenumber)
with open(filename, 'w') as f:
print(x, y, z, '=>', model.norm(), file=f)
which will create or overwrite any files called literally β1β, β2β, β3β,
etc in the current directory. If you want a more meaningful file name,
or to write to another location, change the filename = ... line to
suit your needs.
Ok got it by writing filename+β.txtβ. Now let say I have a similar program which need two operator oupput means
model.operation1 #that produces some output which is used by operation2
model.operation2
Not I want to print
print(x,y,z,β=>β,model.operation1,\n model.operation2,file=(my specified folder)f
How to write that