如何在python中安排输出文件

时间:2018-12-13 12:01:46

标签: python

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

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列。

2 个答案:

答案 0 :(得分:0)

这将为您提供良好的对齐输出。

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

答案 1 :(得分:-1)

您去哪里

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)