Skip to content
Advertisement

Cannot redirect python script output to infile

I am working on Debian Stable Linux which is otherwise working very well. I have following code in a python script file named “myrev” which works to reverse order of lines of given text file:

JavaScript

It works properly and prints out reverse order of lines if I use following Linux command

JavaScript

However, if I try to redirect output with following command to original file, a blank file is generated:

JavaScript

After above command, infile becomes an empty file.

Why can’t I redirect output to original file and how can this be solved?

Advertisement

Answer

Using > opens the target file for write, same as if opened via fopen with mode "w". That immediately truncates the file, before your program even launches (it happens while the shell is configuring the environment before execing your program). You can’t use this approach to read from a file and replace it as a single step. Best you could do would be something like:

JavaScript

where, if the command succeeds, you complete the work by replacing the original file with the contents of the new file.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement