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:
JavaScript
x
13
13
1
#Connect to the database
2
testDBCon = sqlalchemy.create_engine('xxx')
3
4
#Choose what query to select a column from
5
query = "SELECT * FROM testDB.dbo.PIESData;"
6
7
#Choose to print out all rows and columns Selected
8
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
9
df = pd.read_sql(query, testDBCon)
10
11
#Prints out only PartNumber and converts it to a string and prints all the values in every row
12
print( df[['PartNumber']].to_string() )
13
I was thinking of newfile.write( df[['PartNumber']].to_string() )
however that did not work.
Thank you for your help
Advertisement
Answer
Depending on what type of file, pandas supports many formats For a simple csv file you can do:
JavaScript
1
2
1
df.to_csv('file.csv', columns = ['PartNumber'], index = False)
2