Home > Software design >  how to delete space from tuple in python code?
how to delete space from tuple in python code?

Time:02-02

I have a python code that connects to an oracle database and by using select returns me data and saves data in the file. I need to remove spaces in this saved data! Here is my code

import cx_Oracle

conn_str = u'login/password@ip/user'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u"SELECT * FROM subs_histories WHERE subs_subs_id IN (SELECT subs_subs_id FROM subs_histories where end_date < start_date GROUP BY subs_subs_id HAVING COUNT(*) > 1)  ORDER BY subs_subs_id, start_date, end_date")

with open('subs_histories.cvs', 'w', encoding="utf8") as f:
    for row in c:
        print(row[0],";", row[1],";", row[2],";", row[3],";", row[4],";", row[5], file=f)
conn.close()

CodePudding user response:

Use the csv module (it's built into Python) to create CSV files. There are tons of examples on the Internet and there's documentation, it's easy to learn. – Tomalak

CodePudding user response:

You can use the map function to run rstrip and lstrip on each of the tuple elements before you write it to the text file

Convert your example text back in to a tuple (in your case you would just use row)

d1 = "10065 ; 13 ; 1195 ; 2019-01-30 17:32:59 ; 2019-01-31 11:52:57 ; CC:OAPI:boris"
d2 = tuple(d1.split(';'))

Which give us a tuple still containing spaces

('10065 ', ' 13 ', ' 1195 ', ' 2019-01-30 17:32:59 ', ' 2019-01-31 11:52:57 ', ' CC:OAPI:boris')

To remove the spaces, do the following.

no_spaces = tuple(map(lambda x: x.rstrip().lstrip(), d2))

This means, for every element inside d2, run the anonymous/lambda function to remove the spaces to the left and to right of the text and put each value back in to a tuple.

Results in

('10065', '13', '1195', '2019-01-30 17:32:59', '2019-01-31 11:52:57', 'CC:OAPI:boris')

As has been said in the comments, you can use the csv writer to output the data as a csv file (but specifying the seperator as a semi-colon) but that wasn't your question.

Modifying your original example (I don't have oracle to run so this is a guess)

import cx_Oracle

conn_str = u'login/password@ip/user'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute(u"SELECT * FROM subs_histories WHERE subs_subs_id IN (SELECT subs_subs_id FROM subs_histories where end_date < start_date GROUP BY subs_subs_id HAVING COUNT(*) > 1)  ORDER BY subs_subs_id, start_date, end_date")

with open('subs_histories.cvs', 'w', encoding="utf8") as f:
    for row in c:
        row = tuple(map(lambda x: x.rstrip().lstrip(), row))
        print(row[0],";", row[1],";", row[2],";", row[3],";", row[4],";", row[5], file=f)
conn.close()
  •  Tags:  
  • Related