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:

#! /usr/bin/python3 

import sys

if len(sys.argv) < 2: 
    print("Usage: myrev infile")
    sys.exit()
try:
    with open(sys.argv[1], "r") as f:
        lines = f.read().split("n")
except: 
    print("Unable to read infile.")
    sys.exit()

lines.reverse()
print("n".join(lines))

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

./myrev infile

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

./myrev infile > infile

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:

./myrev infile > infile.tmp && mv -f infile.tmp infile

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