我有一个按行和列组织的文本文件。这是文件的样本
ATOM 1 N MET A 0 7.721 14.287 22.993 1.00 56.77 N
ATOM 2 CA MET A 0 8.721 15.393 22.939 1.00 56.81 C
ATOM 3 C MET A 0 10.044 14.985 23.585 1.00 54.96 C
ATOM 4 O MET A 0 11.059 15.660 23.408 1.00 56.23 O
ATOM 5 CB MET A 0 8.167 16.640 23.642 1.00 59.72 C
ATOM 6 CG MET A 0 7.207 16.349 24.796 1.00 62.33 C
ATOM 7 SD MET A 0 5.772 17.459 24.822 1.00 66.48 S
我想做的是在每行的末尾添加一个随机的true或false,最好在其自己的列中,如下所示
ATOM 1 N MET A 0 7.721 14.287 22.993 1.00 56.77 N True
ATOM 2 CA MET A 0 8.721 15.393 22.939 1.00 56.81 C False
ATOM 3 C MET A 0 10.044 14.985 23.585 1.00 54.96 C False
ATOM 4 O MET A 0 11.059 15.660 23.408 1.00 56.23 O False
ATOM 5 CB MET A 0 8.167 16.640 23.642 1.00 59.72 C True
ATOM 6 CG MET A 0 7.207 16.349 24.796 1.00 62.33 C False
ATOM 7 SD MET A 0 5.772 17.459 24.822 1.00 66.48 S False
这是我为实现此目的而编写的功能
def random_TF(pdbFileName): #This function will randomly generate TRUE or FALSE
with open(pdbFileName, 'r') as e:
with open('1fkqTF.txt', 'w') as f:
for i, line in enumerate(e):
line = line.rstrip('\n')
line += str(random.choice([True, False]))
e.close()
f.close()
但是,当我调用该函数时,它将返回一个空白文本文件。
最佳答案
您忘记了f.write(line)
。我添加了'\ n'和'\ t'来改善格式。
def random_TF(pdbFileName): #This function will randomly generate TRUE or FALSE
with open(pdbFileName, 'r') as e:
with open('text2.txt', 'w') as f:
for i, line in enumerate(e):
line = line.rstrip('\n')
line += '\t' + str(random.choice([True, False])) + '\n'
f.write(line)
e.close()
f.close()
关于python - 在Python中每行的末尾附加随机的True或False,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53287296/