I am trying to write the contents of a list to a single column in a csv file. While I have done this in the past, I am not able to get this script to work. Instead I all of the columns filled instead of the rows
#getting values for p vlue of 1%-100%
a = [numpy.arange(.01,1.01,.01)]
for i in a:
with open("GFOLD_Hisat2.csv", 'wb') as file3:
filewriter = csv.writer(file3)
filewriter.writerow(score(list1, list2, i))
Where score() is a function that outputs an integer
Any thoughts on what I should modify?
答案 0 :(得分:3)
Ignoring the questions of what list1
and list2
are (they are irrelevant if score()
returns a single integer), I think the problem lies in your loop structure.
Instead of
for i in a:
with open("GFOLD_Hisat2.csv", 'wb') as file3:
filewriter = csv.writer(file3)
filewriter.writerow(score(list1, list2, i))
You probably want
with open("GFOLD_Hisat2.csv", 'wb') as file3:
filewriter = csv.writer(file3)
for i in a:
filewriter.writerow((score(list1, list2, i),))
At present you are opening the file and creating a new writer for each value of i
. Note that I have turned the result of score
into a tuple
.
In [8]: a = [1,2,3,4,5]
In [9]: with open('a.csv', 'wt') as f:
wr = csv.writer(f)
for i in a:
wr.writerow((i,))
...:
In [10]: !cat a.csv
1
2
3
4
5
I'm also not sure why you are opening the file with 'wb'
As Rob points out, you can just use a comprehension - avoiding the loop completely. My answer is focused on explaining the mistake in your existing code.
Also, if your output file is really only going to contain a single column there's little reason to use a csv.writer
. Simply do the following
a = [1,2,3,4,5]
b = [score(list1, list2, i) for i in a]
with open('a.csv','wt') as f:
f.writelines('\n'.join(map(str,b))
答案 1 :(得分:0)
You have to change the order of the file opening and the loop:
a = [numpy.arange(.01,1.01,.01)]
with open("GFOLD_Hisat2.csv", 'wb') as file3:
filewriter = csv.writer(file3)
for i in a:
filewriter.writerow(score(list1, list2, i))