0

I want to extract data from mysql db and save it on csv file, problem is in my db is present values with \n (new lines). i want to replace this new lines with " " or \n, my curent code is :

def cauta_db(domain_ip, db_username, db_password):
        db = MySQLdb.connect(host=domain_ip, user=db_username, passwd=db_password)
        cur = db.cursor()
        cur.execute(sql_cmd_select_db)
        for database in cur.fetchall() :
            cur.execute("USE {};".format( database[0]) )
            cur.execute("SELECT * FROM {};".format(database[1]))
            file_to_save = creaza_dir(domain_ip, database[0], database[1])

            with open(file_to_save,'wb') as out:
                csv_out = csv.writer(out, delimiter =';', lineterminator='\n')
                for row in cur.fetchall():
                    csv_out.writerow(row)

how i can replace new lines present in database and replace with \\n or space ?

1 Answer 1

2

You may want to check out method rstrip

The method rstrip() returns a copy of the string in which all chars have been stripped from the end of the string (default whitespace characters).

Since tuples are immutable create a list with rstrip()'ed tuple elements and then cast that list as a tuple and write it to file:

    for row in cur.fetchall():
      r = []
      for v in row:
        r.append(v.rstrip())
      row = tuple(r)
      csv_out.writerow(row)
Sign up to request clarification or add additional context in comments.

2 Comments

Could You please clarify where are the new line characters, then? At the end of each element in the tuple?
i want to replace new line from each element in the tuple.

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.