1

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.

Thank you for your help

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

it works however with each lien there is a count like 0,XXX 1,XXX... how would I get ride of this count (78,X01CJ0030 79,X01CJ0031 80,X01CJ0032 81,X01CJ0034 82,X01CJ0035)
try to use : index = False, i have edited the answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.