Python 将数据写入文本文件,然后中途更改

Python 将数据写入文本文件,然后中途更改,python,Python,我试图将数据写入下一个文件,但中途更改了列的一个值,该值对于第一组行是常量。这是我的代码: import random import time start_time = time.time() #time measurement numpoints = 512 L = 20 d = 1 points = set() # Open f and write with open("question2.xyz","w") as f: f.write("%d\ncomment goes her

我试图将数据写入下一个文件,但中途更改了列的一个值,该值对于第一组行是常量。这是我的代码:

import random
import time

start_time = time.time() #time measurement
numpoints = 512
L = 20
d = 1
points = set()

# Open f and write
with open("question2.xyz","w") as f:
    f.write("%d\ncomment goes here\n" % numpoints) #this is for the 2nd line in my xyz 
    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)
提前谢谢你的帮助

编辑,woops抱歉,这是我想要实现的

512 #number of
comment goes here
H 6.000000 19.000000 14.000000
H 11.000000 2.000000 7.000000
H 15.000000 20.000000 16.000000
O 6.000000 19.000000 14.000000
O 11.000000 2.000000 7.000000
O 15.000000 20.000000 16.000000

现在,我的代码为所有512行的第一个值输入H,从第256行开始,我需要将其更改为O,您可以使用一个生成器生成点,并使用两个
进行
循环:

def pointgen(used):
    while True:
        p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
        if p not in used:
            used.add(p)
            yield p

# Open f and write
with open("question2.xyz","w") as f:
    f.write("%d\ncomment goes here\n" % numpoints) #this is for the 2nd line in my xyz 
    pg = pointgen(points)
    for i in xrange(numpoints // 2):
        f.write('H %f %f %f\n' % pg.next())
    for i in xrange(numpoints // 2):
        f.write('O %f %f %f\n' % pg.next())

您还可以发布您希望实现的示例吗?您可以发布示例输入文件和预期输出吗..没有输入文件,将生成该文件并显示如上所示的输出文件
def pointgen(used):
    while True:
        p = (random.randint(0, L), random.randint(0, L), random.randint(0, L))
        if p not in used:
            used.add(p)
            yield p

# Open f and write
with open("question2.xyz","w") as f:
    f.write("%d\ncomment goes here\n" % numpoints) #this is for the 2nd line in my xyz 
    pg = pointgen(points)
    for i in xrange(numpoints // 2):
        f.write('H %f %f %f\n' % pg.next())
    for i in xrange(numpoints // 2):
        f.write('O %f %f %f\n' % pg.next())