Delete particular string while reading CSV data
Question: I'm new in python , and I'm writing a code to read data from a CSV file.

The data looks like this:

    
    
    10944750,13451,0,6��4��   
    
    10944750,21110,0,6��7��
    
    10944750,1131,0,7��23��
    
    10944750,8689,0,5��2��
    

The last column represents date , for example in first row : June 4th . But
there are two Chinese charter in it . So I have to decode it and get the month
and day.

My code :

    
    
    import codecs
    raw_file=open('Documents/t_alibaba_data.csv')
    result=open('Documents/result.txt','w')
    for line in raw_file.readlines():
        entry=line.split(",")
        deco=entry[3].decode("gbk")
        month=deco[0]
        if len(deco)==5:
            day=int(deco[2])*10+int(deco[3])
        else:
            day=int(deco[2])
        result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
            print result
    

There is no alert or error in my IDE, but there is nothing in my result
either.


Answer: First of all: you haven't told Python that you want to read from the file.
(add 'r' to raw_file.open().

And, when running your program, after decoding the last column, element nr 3
(deco[2]) is a chinese symbol, not the nr of day.

I adjusted your program a little, and when it looks like this, it works (at
least if I understood your question correctly):

    
    
    import codecs
    raw_file=open('Documents/t_alibaba_data.csv', 'r')
    result=open('Documents/result.txt','w')
    for line in raw_file.readlines():
        entry=line.split(",")
        deco=entry[3].decode("gbk").strip()
        month=deco[0]
        if len(deco)==5:
            day=int(deco[2])*10+int(deco[3])
        else:
            day=int(deco[4])
        result.write(",".join(entry[:3])+","+str(month)+","+str(day)+"\n")
    result.close()
    

Also, len(deco) is never 5, and the if test will never be true. The length is
_always_ longer than 5. Try printing out the length of the different decos to
see what the actual length is. It could be wise to use the strip function on
deco, in case there are spaces at the end of the string. When I print the
length of the decos you gave as examples, the length was 8 or 9, depending on
the line that were being processed.

