Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting SQL Column to print in Python

I have a code that prints out a specific column from an SQL query table. It prints out fine however I would like it to be put into a file and I cannot think of how to do that.

Here is what I have:

#Connect to the database
testDBCon = sqlalchemy.create_engine('xxx')

#Choose what query to select a column from
query = "SELECT * FROM testDB.dbo.PIESData;"

#Choose to print out all rows and columns Selected
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    df = pd.read_sql(query, testDBCon)

#Prints out only PartNumber and converts it to a string and prints all the values in every row
print( df[['PartNumber']].to_string() )

I was thinking of newfile.write( df[['PartNumber']].to_string() ) however that did not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you for your help

>Solution :

Depending on what type of file, pandas supports many formats For a simple csv file you can do:

df.to_csv('file.csv', columns = ['PartNumber'], index = False)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading