By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,516 Members | 936 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,516 IT Pros & Developers. It's quick & easy.

Output strings to directory locally

P: 3
Is it possible to output strings created from a print statement into a directory locally?
If so, would you use sysstdout module?
Sep 8 '14 #1
Share this Question
Share on Google+
7 Replies

Expert Mod 2.5K+
P: 2,851
You can assign sys.stdout to an open file object.
Expand|Select|Wrap|Line Numbers
  1. f = open("test.txt", 'w')
  2. sys.stdout = f
Subsequent print statements will direct the output to the open file.
Sep 8 '14 #2

P: 3
Thank you! However, my files do not have a .etc extension. They are unique and I need them to actually be propagated straight into a directory. Is this possible?
Sep 8 '14 #3

Expert Mod 2.5K+
P: 2,851
It's a good idea to save the old value of sys.stdout and restore it when you are done.
Expand|Select|Wrap|Line Numbers
  1. stdout_old = sys.stdout
  2. sys.stdout = open("test.txt", 'a')
  3. # do stuff
  4. sys.stdout = stdout_old
Sep 8 '14 #4

Expert Mod 2.5K+
P: 2,851
Not that I know of. Information is stored on disc in files. A directory is not a file. BTW, File objects don't have to have extensions.
Sep 8 '14 #5

Expert 100+
P: 626
If you are running linux you can pipe standard output to a file directly > output_print_file.txt
Sep 8 '14 #6

P: 3
So I tried the sysstd output with this code
Expand|Select|Wrap|Line Numbers
  1. import os
  3. path = '/Users/felishalawrence/testswps/vol1'  
  4. for file in os.listdir(path):
  5.         newFile = file[:file.rindex("v")]+"v20"
  6. sys.stdout =  '/Users/felishalawrence/testswps/vol1'
  7. print newFile
and got nothing. No errors and it did not print out my results in ipython notebook when I removed line 5 and ran it again. The output was also not in the folder specified. What did I do wrong? Can I reset it? If so, how?
Sep 9 '14 #7

Expert Mod 2.5K+
P: 2,851
In your for loop, you define a value to identifier "newfile", but you perform no action with this value. After the for loop, you assign sys.stdout to a directory when it should be assigned to an open file object. The following print statement goes nowhere.
Sep 15 '14 #8

Post your reply

Sign in to post your reply or Sign up for a free account.