Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Error and I don't know why?
#1
Hello; Im trying to make a code that converts a specific column into binary.
I keep on getting an error code.
Could Someone tell me what I am doing wrong please?
thank you.
btw the type of file i am dealing with is a SAM file
import re 
import csv


f = 'filedirectory'
d = '\t'
g=open(f,'r')
reader = csv.reader(g,delimiter=d)
ncol=len(next(reader))
f.seek(0)

indata = open("filedirectory")
for line in indata:
    print (bin(int(line.split()[1])), ', ', [1], ', ', [5])
Reply
#2
Please, post full traceback in error tags.
Reply
#3
I would restructure your code to make it easier to debug:
import csv

def convToBin(filename, mode='r', delim=','):
    with open(filename, mode) as csvfile:
        csvreader = csv.reader(csvfile, delimiter=delim)
        for row in csvreader:
            for item in row:
                print(bin(int(item)))

def main():
    myfile = 'myfile.csv'
    convToBin(filename=myfile)

if __name__ == '__main__':
    main()
i created a file which looks like:
Output:
123,456,789 22,25,76
When run through above code, results are:
Output:
0b1111011 0b111001000 0b1100010101 0b10110 0b11001 0b1001100
Reply
#4
Thank you Larz 60+

just a quick question, what did i do wrong with my code?

thanks.
Reply
#5
not sure, but trying to do too much in one line.
print (bin(int(line.split()[1])), ', ', [1], ', ', [5])
It's difficult to read, so better splitting into multiple lines.
Reply
#6
Thank you so much Larz60+. Just one last question on this thread; do you know if that last line is the correct way to output the following,

binary version of column 1, column one, column five
Reply
#7
Do you know if there will always be a column 5?
since each row is a list, you should be able to reference the columns as row[0] (first column)
and row[4] (fifth column) remember the index is zero based. If you are going to do this, I'd
prefix the print with:
if len(row) > 4:
    ...
or surround with a try ... except clause
Reply
#8
Gotcha. Thank you so much.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020