my first time writing python script. I had read through many questions and answers in stack overflow, but still didn't figure out where I got wrong in my code. Probably I could ask for help?
I have a file file.txt as below, with uncertain number of column in each line. "\t" is the tab delimiter
$ head file.txt
AA:d23\tBB:4r3w\tCC:e5t
BB:435\tCC:w4w
AA:w4r\tCC:2342
AA:34534\tBB:e5\tCC:7uf
BB:e4t4
I would like to turn it into a data_frame like .txt file, which has three columns in each row by adding NA for the missing column. Also, I would like to eliminate the rows that only have one entry (e.g. only AA or only BB or only CC). So expected output like below:
AA:d23\tBB:4r3w\tCC:e5t
AA:NA\tBB:435\tCC:w4w
AA:w4r\tBB:NA\tCC:2342
AA:34534\tBB:e5\tCC:7uf
#(the 5th line is omitted here because it only has one entry)
After studying many examples on the forum,I mimicked some codes, and wrote my own code as below:
#!/usr/bin/env python3
#into_data.py
import csv
def into_data(a_file):
output=[]
for row in a_file:
if "AA:" in row and "BB:" in row and "CC:" in row:
output.append(row)
elif "AA:" not in row and "BB:" in row and "CC:" in row:
output.append("AA:NA" + row)
elif "AA:" in row and "BB:" not in row and "CC:" in row:
output.append(row.split("\t")[0] + "CB:NA" + row.split("\t")[1])
elif "AA:" in row and "BB:" in row and "CC:" not in row:
output.append(row + "CC:NA")
reader = csv.reader(fileinput.input(), delimiter="\t")
print(into_data(reader))
#outside python script
python3 into_data.py file.txt > output.txt
But I get "None" in my output.txt. I don't really understand why. Could you please be so kind to point my error out? Thanks a lot in advance!