0

I have a small script which download me a results from query and export it to .csv

yy = raw_input("Enter year: ")
mm = raw_input("Enter month: ")

try:

    conn = psycopg2.connect("dbname='xxx' user='xxx' host='xxx' password='xxx'")
    cur=conn.cursor()

 query1 = """SELECT name FROM xxx where name like '%{0}_{1}%' """.format(yy,mm)
        cur.execute(query1)
        results = cur.fetchall()
        for row in results:
        print row

csv_file = open('errors.csv','wb')# wb - query importing line by line
myFile = csv.writer(csv_file)
myFile.writerows(results)
csv_file.close()

What i need is a part of string from query results. Atm my results looks like this:

1-GRB-804_2016_02_03__08_42_12
1-GRB-804_2016_02_05__11_04_47
1-GRB-804_2016_02_06__08_20_15
1-GRB-804_2016_02_08__08_06_13
1-GRB-804_2016_02_08__08_30_58

And what i want is to get first line untill it meet sign '_'. So results will be :

1-GRB-804
1-GRB-804
1-GRB-804
1-GRB-804
1-GRB-804

Regards

1 Answer 1

1

You want to keep everything until the first “_”, you can simply use string.split:

>>> s = '1-GRB-804_2016_02_03__08_42_12'
>>> s.split('_')
['1-GRB-804', '2016', '02', '03', '', '08', '42', '12']
>>> s = s.split('_')[0]
>>>> s
'1-GRB-804'

So in your case, you would need to do:

for row in results:
    print row.split('_')[0]
Sign up to request clarification or add additional context in comments.

1 Comment

what if i use both queries from postgres and microsoft sql server ? If i join their results in to one ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.