0

I am working on a new project. I want to connect the database, download the file from here and upload it again after making changes. But there is a problem. When I pull the data with Python, the result should be exactly the same. However, when I open the file, I see that the spaces are removed, adds parentheses to the beginning and end, the UTF-8 structure is broken, and the lines are completely removed. Why is this happening and how can it be resolved?

My Code:

# -*- coding: utf-8 -*-
f = open('sonuc.txt','w', encoding='utf-8')
import MySQLdb

db=MySQLdb.connect(host='host',user='usr',password='ps',db='db',)

mycursor = db.cursor()
mycursor.execute('SELECT message FROM mybb_posts WHERE pid=1;')
sonuc = mycursor.fetchall()
f.write(str(sonuc))
f.close()

The original data is as follows:

Lets Try This!
Line 2
Line 3
Try other charecter:
like "ş", "i", "ü", "ğ", "İ"
Line 6

Python result (sonuc.txt):

(('Lets Try This!\r\nLine 2\r\nLine 3\r\nTry other charecter:\r\nlike "?", "i", "ü", "?", "?"\r\nLine 6\r\n',),)

Edit: for UTF-8 problem, add charset='utf8mb4', to MySQLdb.connect()

0

1 Answer 1

1

There's nothing corrupt about that. That's just the Python representation of an 1-tuple containing an 1-tuple containing a string, since .fetchall() returns a tuple of tuples with the columns you requested.

If you want to write the first column of each row returned by your query,

for row in mycursor:
    message = row[0]
    f.write(message)
f.close()

While you're at it, you should practice proper open hygiene:

import MySQLdb

with MySQLdb.connect(
    host="host",
    user="usr",
    password="ps",
    db="db",
) as db:
    mycursor = db.cursor()
    mycursor.execute("SELECT message FROM mybb_posts WHERE pid=1;")
    with open("sonuc.txt", "w", encoding="utf-8") as f:
        for row in mycursor:
            message = row[0]
            f.write(message)
Sign up to request clarification or add additional context in comments.

Comments

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.