Bello Daniel
Bello Daniel

Reputation: 33

python save data on csv file and replace new lines

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 ?

Upvotes: 0

Views: 45

Answers (1)

user10259046
user10259046

Reputation:

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)

Upvotes: 2

Related Questions