Python Forum
How to select NULL and blank values from MySQL table into csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to select NULL and blank values from MySQL table into csv
#8
I really messed up my previous post during an edit. No wonder you couldn't figure out what it was supposed to do.
Sorry about that. The code should look like this:
import pandas as pd

odd_stuff = pd.DataFrame([[1, '1', 'one', None, ''], [2, '2', '', None, None]])

def df_to_csv(dataframe, csv_file, sep=','):
    """Write dataframe to csv file using special conventions.
    1: All values except None are surrounded by double quotes.
    2: None will appear as a blank.
    """
    with open(csv_file, "w") as file:
        for row in dataframe.values:
            row_str = sep.join(['' if x is None else f'"{x}"' for x in row])
            print(row_str, file=file)

df_to_csv(odd_stuff, "test.csv", sep='|')
First it creates a list of str objects from the objects in a row. None becomes an empty str and anything else becomes str(obj) wrapped in double quotes. Next I join all the str objects together separated by sep.

Hope this is clear now.
python300 likes this post
Reply


Messages In This Thread
RE: How to select NULL and blank values from MySQL table into csv - by deanhystad - Dec-27-2022, 08:24 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Mysql and mysql.connector error lostintime 2 858 Oct-03-2023, 10:25 PM
Last Post: lostintime
  How to express null value klatlap 3 1,010 Mar-25-2023, 10:40 AM
Last Post: klatlap
  Replacing values ​​in Mysql with a condition stsxbel 0 712 Mar-05-2023, 08:20 PM
Last Post: stsxbel
  Mysql Workbench table not updated CatBall 2 1,254 Feb-13-2023, 05:37 PM
Last Post: CatBall
  Write Null values as 0.0 (float) type in csv mg24 3 1,639 Dec-07-2022, 09:04 PM
Last Post: deanhystad
  store all variable values into list and insert to sql_summary table mg24 3 1,295 Sep-28-2022, 09:13 AM
Last Post: Larz60+
  Mysql error message: Lost connection to MySQL server during query tomtom 6 16,874 Feb-09-2022, 09:55 AM
Last Post: ibreeden
  value null when update in json file 3lnyn0 6 3,772 Dec-30-2021, 05:52 PM
Last Post: ndc85430
  Sum the values in a pandas pivot table specific columns klllmmm 1 4,859 Nov-19-2021, 04:43 PM
Last Post: klllmmm
  SaltStack: MySQL returner save less data into Database table columns xtc14 2 2,277 Jul-02-2021, 02:19 PM
Last Post: xtc14

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020