0

I am having a bit of an issue printing my python output to a txt file. I am currently running a script as such:

import glob import pandas as pd files = glob.glob('*.txt') result = pd.DataFrame() for file in files: df = pd.read_csv(file,delimiter=' ') current_col = df.columns[0] df.reset_index(inplace=True) df.set_index(current_col,inplace=True) df.index.name = 'index' df.rename(columns={'index':current_col}, inplace=True) result = pd.concat([result,df],axis=1) 

I then eventually get the output I am looking for with:

>>> result >>> result.fillna(0) 

But I would like to get these results to print to a txt file. I am currently running these commands in the terminal on a mac with python v3.7.4. I have tried opening a text file and writing the results to the text file with no success:

import glob import pandas as pd file = open('counts.txt','w') files = glob.glob('*.txt') #eg: files = ['1.txt','2.txt'] result = pd.DataFrame() for file in files: df = pd.read_csv(file,delimiter=' ') current_col = df.columns[0] df.reset_index(inplace=True) df.set_index(current_col,inplace=True) df.index.name = 'index' df.rename(columns={'index':current_col}, inplace=True) result = pd.concat([result,df],axis=1) file.write(result +'\n') 
1
  • why not just use result.to_csv('counts.txt',sep=' ') or something similar? Commented Nov 12, 2019 at 21:10

1 Answer 1

1

When you are done building result, just put it in a print statement like so:

print(result) 

And then you can run your file like this:

$ python your_script.py >> /path/for_output_file.txt 

It redirects all your print statements to the specified file.

If you use a single operator >, it will overwrite the results. So use >> to append.

Sign up to request clarification or add additional context in comments.

4 Comments

what print statements
That was a general explanation of the redirection operator.
that is great..but running that command with this python file would do nothing
I see your point. My bad. Just edited my code to reflect that. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.