1

I have a python script that reads from a csv file and prints to stdout. It is necessary that the default output is to stdout, not directly to a file. When I execute this script in bash, like so:

program.py > file.csv

where the output file.csv is the same that the python script is reading from, it fails. The reason is that bash apparently erases the file.csv before executing the python program. How can I execute this in bash so that the file would be erased after the python program finishes executing?

1 Answer 1

2

You could do something ugly like

program.py > tmp.csv && mv tmp.csv file.csv
7
  • Wouldn't program.py > tmp.py; mv tmp.py file.csv be more appropriate in this case? Also, it would be better to not create more files than needed, because this is running on a SD card and I believe it shortens its lifespan.
    – shrx
    Feb 13, 2013 at 15:46
  • @shrx -- It really depends on how you want to handle the case where program.py doesn't exit cleanly. Personally, I wouldn't want to overwrite my input file unless I knew for a fact that the program successfully created another.
    – mgilson
    Feb 13, 2013 at 15:47
  • @shrx -- I don't see how you can neatly avoid the temporary file without modifying your python script to hold the results internally and then dump them (to a file, not stdout) just before exiting.
    – mgilson
    Feb 13, 2013 at 15:51
  • 1
    The SD card is probably distributing any writes across all available blocks (i.e., it isn't constantly using the same area of the card and leaving other areas untouched), so unless the card is being used for something like swap, it's not an issue. (And if it is being used for swap, your creation of a new file here and there is not a significant source of wear.)
    – chepner
    Feb 13, 2013 at 15:53
  • 1
    While a collision with something else creating a temp file in this case may not be likely, adding the process ID to the file name is cheap insurance: program.py > tmp-$$.csv && mv tmp-$$.csv file.csv
    – William
    Feb 13, 2013 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.