将随机生成的数字放入文本文件中

时间:2012-10-03 04:16:00

标签: python

我的任务是在一个尺寸为20x20x20的方框内生成随机坐标(其中512个)。

观看此3D图像的程序需要XYZ文件格式为:

1000.000000 #number of coordinates
comment goes here #coment line
H 0.000000 0.000000 0.000000 #1st colmun is arbitary - we'll leave it H, 2nd is x vavlue, 3rd value is y value and 4th column is z value.
H 0.000000 0.000000 1.000000
H 0.000000 0.000000 2.000000
H 0.000000 0.000000 3.000000

到目前为止,我有,

import random
numpoints=512
L=20
while len(points)<numpoints:
    p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
    if p not in points:
        points.add(p)

这将生成我的(x,y,z)坐标,但我遇到的问题是将它放入文本文件中。

我从这样的事情开始,但需要一些帮助:

with open("question1.xyz","w") as file:
     file.write("\ncomment goes here\n") #this is for the 2nd line in my xyz file
     while len(points)<numpoints:
        p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
        if p not in points:
            points.add(p)
                    file.write('H %f %f %f\n' % (x, y, z))

这是我必须创建我的输出并将行数放在第一行但是出于某种原因它不能模拟我的文件

#this will put the number of particles as the first line and generate an output file
with open("question2.xyz") as infile:
    with open("q2Output.xyz","w") as outfile:
        for i,line in enumerate(infile):
            if i==0:
                outfile.write('%f\n'%counter)
            else:
                outfile.write(line)

我想出了因为我的计数器不存在,但是有更有效的方法吗?

2 个答案:

答案 0 :(得分:2)

这可以清理一下,但基本的改变是:

  1. 添加points容器
  2. file更改为f(您希望避免使用与内置Python相同的名称定义变量),
  3. 更改format参数以接受元组p(它将自动解压缩)
  4. 进行一些基本的格式更改。
  5. 总而言之,你非常接近 - 只需要调整一些基本的东西。

    import random
    
    numpoints = 512
    L = 20
    points = set()
    
    # Open f and write
    with open("question1.xyz","w") as f:
        f.write("\ncomment goes here\n") #this is for the 2nd line in my xyz f
        while len(points) < numpoints:
            p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
            if p not in points:
                points.add(p)
                f.write('H %f %f %f\n' % p)
    

    以下不是更有效,但引入了递归的概念以生成随机点。以前的版本运行得很好 - 这更有趣:)

    import random
    
    numpoints = 512
    L = 20
    points = set()
    
    def RandomPoint(points):
        p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
        if p in points:
          p = RandomPoint(points)
        return p
    
    # Open f and write
    with open("question1.xyz","w") as f:
        f.write("\ncomment goes here\n") #this is for the 2nd line in my xyz f
        for point in xrange(0, numpoints):
            p = RandomPoint(points)
            points.add(p)
            f.write('H %f %f %f\n' % p)
    

答案 1 :(得分:1)

尝试这样的事情:

fh = open('filename', 'w')
fh.write(str(len(points)) + '\n')
fh.write("comment goes here\n")
for point in points:
    fh.write("H %1.6f %1.6f %1.6f\n" % (point[0],point[1],point[2]))
fh.flush()
fh.close()