Home > database >  .csv TypeError: object of type '_io.TextIOWrapper' has no len() and averaging rows
.csv TypeError: object of type '_io.TextIOWrapper' has no len() and averaging rows

Time:10-17

I have to create a module that reads in an RNA-seq counts table (counts_table.csv) line by line, computes the average number of counts across each gene_ID, and writes the original table contents, in addition to the average counts in a new column, to a new file. My code cannot contain any import statements. This is what I have so far for my function:

def count_average(input_file, output_file):
try:
    fin = open(input_file, "w")
    fout = open(output_file, 'w')
except:
    return -1 
with fin, fout:
    sums = []
    averages = []
    for i in range(len(fin)):
        sums.append(0)
        for n in range(len(fin[i])):
            sums[i]  = fin[i][n]
            averages[i]  = sums[i]/[n]
    for line in fin:
        fout.write(line)
        fout.append(averages)

I know I am successfully opening the files and I can append all of the information of the infile to the outfile however I have two things I am stuck on.

  1. I keep getting TypeError: object of type '_io.TextIOWrapper' has no len()
  2. I am not sure if my code will properly append the averages and I don't know how to make a new average header on top of those

Ultimately I want the final result to look something like this: Input_to_Output

CodePudding user response:

The problem in your code is that you are opening the file in wrong way. Instead of writing this:

fin = open(input_file, "w")

Write this:

fin = open(input_file, "r")

CodePudding user response:

would be much easier to provide a working example if you had posted your actual data.

The problem is this line:

for i in range(len(fin)):

and this line:

for n in range(len(fin[i])):

To iterate over every line/row in your file, use something like this instead:

for row in fin:

and then:

 for cell in row:
  • Related