Appending random True or False to the end of each line in Python

Viewed 67

I have a text file that is organized into lines and columns. Here is a sample of the file

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  

What I want to do is to add a random true or false to the end of each line, ideally in its own column, something that looks like this

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

Here is the function that I have written to try to accomplish this

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()

However, when I call the function it returns a blank text file.

2 Answers

you forgot f.write(line). I've included '\n' and '\t' to improve the formatting.

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()

You aren't actually writing to the file. You need to call:

f.write(line + "\n")

after you have updated the line.

Also, you don't need to call e.close() or f.close(), that's the advantage of using the context manager with.

Finally, there is likely a better way to do what you are doing using a proper data manipulation library such as pandas, but without additional context as to why you are doing this it will be tough to provide much insight.

Related