0

I am redirecting my prints from a python script to a new file with this:

sys.stdout= open('/home/miriam/Dokumente/Atom/python/results.txt',"w")

instead of "results.txt", I want to name the file using a variable I read from stdin. What I want is something like:

var=sys.argv[1]

sys.stdout= open('/home/miriam/Dokumente/Atom/python/var_results.txt',"w")

Is there a way to do this? I tried it with escaping with backslashes, but couldnt figure it out

This might be a duplicate, but I could not find anything so far. Thanks in advance :)

Shushiro
  • 577
  • 1
  • 9
  • 32
  • So you format the string with your value then? `f'/home/.../{var}_results'` in 3.6 or `'/home/.../{}_results'.format(var)'` prior – Jon Clements Nov 02 '17 at 11:55
  • Or even such a deprecated thing like `'/home/.../%s_results' % var` :) – devforfu Nov 02 '17 at 11:56
  • You might also want to consider if you're redirecting the entire program - you might as well just pipe the stdout to a file when running, or look at the `contextlib.redirect_stdout` for just specific blocks instead of playing with `sys.stdout` – Jon Clements Nov 02 '17 at 11:57
  • appearently, I am using 3.6, your solution worked, thank you! @JonClements if you want to post an answer I can upvote, do so :) – Shushiro Nov 02 '17 at 11:58

1 Answers1

0

Simply append the desired filename you got from sys.argv to the path:

Filename=sys.argv[1]
TheFile=open("path/to/your/file"+Filename,"w+")
Sim Son
  • 310
  • 1
  • 10
  • 1
    In Python we usually use either string formatting or (for filesystem path stuff) `os.path.join()` instead of string concatenation. And the official naming convention is "all_lower_with_underscores" for variable names. – bruno desthuilliers Nov 02 '17 at 12:16