1

I am self-taught in MySQL, Python and Linux based OS, and quite sure there must be a more elegant solution to the problem, or, at least, one that works along my lines. The code is taking data from the last 24 hours from a database and storing them to a .txt file to be handled further on. However, the output I am getting has additional symbols that are making further analysis troublesome - I want to know if there is a way to remove them.

My (relevant) code is:

    ...
    cur = db.cursor()
    cur.execute("SELECT * FROM Sens WHERE sdate > DATE_SUB(NOW(),INTERVAL 24 HOUR)")
    query = cur.fetchall()

    OutputFile = open("/root/Desktop/data.txt", "w")
    for i in range (0, len(query)):
        print>>OutputFile, query[i]
    ...

The reason I am using for loop is to have each row fetched printed in a newline. The result I get is as follows:

    ('0,01/24/16,12:41:49,45.185\r\r\n',)

The result I need is:

    0,01/24/16,12:41:49,45.185

Much appreciate the help, LZ.

1
  • As i see the results are a tuple first try query[i][0] and if there are still some chars left you can use re to help. Commented Jan 25, 2016 at 16:03

2 Answers 2

1

You could use:

for i in range (0, len(query)):
        print>>OutputFile, query[i][0].strip()

The [0] index selects the string from the tuple, and the strip() function removes the whitespace from the left and right hand side of the string.

Sign up to request clarification or add additional context in comments.

Comments

0

For a start, you shouldn't ever be iterating over range(len(something)). Always iterate over the thing itself. Also, it's more idiomatic to use file.write to output, rather than pritnting.

From there, all you need to do is just output the first element in each item, with [0].

for q in query:
   OutputFile.write(q[0])

3 Comments

I am always looking for quality programming tips, so thank you for them! Should I make q then a variable of the size of the length of query? like q = len(query)
No, the whole point is that there is no need to get the length of the query. Just iterate over it.
wow - i did not know that was even possible. yes, that works perfectly - thank you!!

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.