如何在python中排列输出文件

2024-06-16 14:10:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一段代码,用于在酉球体中生成x,y,z位置。问题是,在输出文件中,它们没有像xyz那样排列在单独的列中

from numpy import random, cos, sin, sqrt, pi 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 

def rand_sphere(n):  
    z = 2 * random.rand(n) - 1   # uniform in -1, 1 
    t = 2 * pi * random.rand(n)   # uniform in 0, 2*pi 
    x = sqrt(1 - z**2) * cos(t) 
    y = sqrt(1 - z**2) * sin(t)   
    return x, y, z

x, y, z = rand_sphere(200)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')  
ax.scatter(x, y, z)
plt.savefig('sphere.png')
#plt.show()

Outfile=open('output.txt','w') 
Outfile.write('This line will be text\n')  
Outfile.write('\n') 
Outfile.write(repr(rand_sphere(200))) 
Outfile.close() 

另一个问题是,在x y z列之前,我需要为每行重复m=10

表示输出文件中的每一行必须如下所示(它们之间没有逗号):

This line will be text
m    x     y     z
20  ...   ...   ... 
.
.
.
(200 lines) 

所以,我想有三个独立的位置列加上一个m=10列。你知道吗


Tags: 文件infromimportpipltrandomuniform
2条回答

给你

x, y, z = rand_sphere(200)
m = 10
# creating lists and storing them in res
# each list contains the elements of a line
res = [ [m, x[i], y[i], z[i]] for i in range(len(x)) ]
data = "This line will be text"
# concatenating line elements 
for elem in res:
    data = "{}\n{}".format( data, ','.join(str(num) for num in elem) ) 

with open(my_file, 'w') as file:
    file.write(data)

这将为您提供一个很好的对齐输出。你知道吗

from numpy import random, cos, sin, sqrt, pi 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 

def rand_sphere(n):  
    z = 2 * random.rand(n) - 1   # uniform in -1, 1 
    t = 2 * pi * random.rand(n)   # uniform in 0, 2*pi 
    x = sqrt(1 - z**2) * cos(t) 
    y = sqrt(1 - z**2) * sin(t)   
    return x, y, z

def col_align(x, y, z):
    data = '{:>3} {:>6} {:>6} {:>6}\n'.format('m', 'x', 'y', 'z')
    for i in range(len(x)):
        data += '{: 3d} {: 05.3f} {: 05.3f} {: 05.3f}\n'.format(10, x[i], y[i], z[i]) 
    return data

x, y, z = rand_sphere(200)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')  
ax.scatter(x, y, z)
plt.savefig('sphere.png')
plt.show()

Outfile=open('output.txt','w') 
Outfile.write('This line will be text\n')  
Outfile.write('\n')
Outfile.write(col_align(x, y, z)) 
Outfile.close()

我只是使用了你的脚本,在编写文件之前对格式输出进行了一些处理。在这里https://pyformat.info/查看有关格式化字符串方法的详细信息,以防您希望调整浮点精度和空格以满足您的需要。你知道吗

仅供参考,以下是我的output.txt文件的第一行:

This line will be text

  m      x      y      z
 10  0.554 -0.826  0.105
 10 -0.501 -0.816 -0.287
 10 -0.774 -0.515 -0.368
 10 -0.537  0.672 -0.510
 10  0.869  0.291  0.401
 10 -0.511  0.806  0.299
 10  0.488 -0.770 -0.412

相关问题 更多 >