[英]Cannot redirect python script output to infile
I am working on Debian Stable Linux which is otherwise working very well. 我正在研究Debian Stable Linux,否则它会很好地工作。 I have following code in a python script file named "myrev" which works to reverse order of lines of given text file:
我在名为“ myrev”的python脚本文件中有以下代码,该文件可以反转给定文本文件的行顺序:
#! /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 如果我使用以下Linux命令,它将正常工作并打印出行的反向顺序
./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. 执行上述命令后,infile变为空文件。
Why can't I redirect output to original file and how can this be solved? 为什么我不能将输出重定向到原始文件,该如何解决?
Using >
opens the target file for write, same as if opened via fopen
with mode "w"
. 使用
>
将打开要写入的目标文件,就像通过fopen
以模式"w"
fopen
时一样。 That immediately truncates the file, before your program even launches (it happens while the shell is configuring the environment before exec
ing your program). 这会在您的程序甚至启动之前立即将文件截断(在
exec
程序之前,shell在配置环境时发生)。 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. 在此,如果命令成功执行,则可以通过将原始文件替换为新文件的内容来完成工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.