How can I print my results in a text file?

Asked

Viewed 48 times

-2

Well, I need to solve some linear systems through the Jacobi method using Python 3.8 programming, I made the code (which I’ll leave below), but I can’t make a print file that stores my results in an organized way. My goals are:

  1. Create a folder and in it a file with the Jacobi function
  2. From another file 'call' this function to solve all linear systems that will be there
  3. Print these results in an organized way, like the figure below Modelo de como devem ser as impressões

import numpy as np
n = 3
A = np.array([(10.0, 3, -2), (2.0, 8, -1), (1.0, 1, 5)])
b = np.array([(57.0), (20.0), (-4.0)])
Toler = 1.0000e-05
IterMax = 50
x = np.zeros((n, 1))
v = np.zeros((n, 1))
Iter = 0
CondErro = 0
for i in range(n):
    r = (1/A[i, i])
    for j in range(n):
        if i != j:
            A[i, j] *= r
    b[i] *= r
    x[i] = b[i]
Iter = 0
while True:
    Iter += 1
    for i in range(n):
        soma = 0
        for j in range(n):
            if i != j:
                soma += A[i, j] * x[j]
        v[i] = b[i] - soma
    NormaNum = 0
    NormaDen = 0
    for i in range(n):
        t = abs(v[i]-x[i])
        if t > NormaNum:
            NormaNum = t
        if abs(v[i]) > NormaDen:
            NormaDen = abs(v[i])
        x[i] = v[i]
    NormaRel = (NormaNum / NormaDen)
    print(f'{Iter}{x}{NormaRel}')
    if NormaRel <= Toler or Iter >= IterMax:
        break
if NormaRel <= Toler:
    CondErro = 0
else:
    CondErro = 1
  • It would not be simpler just to display in the ordinary way and when you want to redirect the default output to a file?

1 answer

0


You can do the following:

buf = "" # cria um buffer para substituir o stdout

buf += "string" # fazer isso ao invés de print("string")

with open("filename", "w") as f:
    f.write(buf)

Or create another file and do this:

import subprocess
p = subprocess.run(["python3", "jacobi.py"], stdout=subprocess.PIPE)
with open("filename", "wb") as f:
    f.write(p.stdout)
  • I could not understand very well, what I need to learn to understand your code and put it into practice in my situation ? lets me put a simpler example to see if you can help me with more details Suppose in the file 1.py: def sum(a, b) sum = a + b Return sum suppose in the file 2: import file1 a = 3 b = 5 archiv1.sum(a, b) >> 8 That said I’d like to learn how to create a file. txt containing the following The value of the first installment a was 3 .

  • I think it would be good if you searched for files in Python, and also Pipes.

  • I’ve done a lot of research on how to write and read python files, function . read and . write, I’ll search this PIPE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.