Beginners confusion about getting individual outputs as individual data file

There is some code

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

1 Like

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

Demo

>>> vals = f"({x}, {y}, {z})"           # f-strings, Python 3.6
>>> write_to_filname(1, vals)
'1.txt'

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.

2 Likes

Dark asked:

β€œ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.

2 Likes

Thats working but how to get .txt formatted files in your modification and how to keep the files let say in-> c:users\dark folder

1 Like

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

1 Like