繁体   English   中英

使用Python subprocess.call()时如何写入文件开头?

[英]How to write to the beginning of a file when using Python subprocess.call()?

我运行以下脚本:

with open("logfile.txt", 'w') as log_file:
    cmd = path + '/somebinary'
    log_file.write("Running the command: %s\n" % cmd)
    subprocess.call(cmd, shell=True, stdout=log_file, stderr=log_file)

但是, cmd变量被写入文件的末尾而不是开头(这是我期待/希望的)。 有人可以向我解释为什么以及如何防止这种情况吗?

我想出了一个这样做的想法,也许你会发现它很有用。

输入:text.txt

123
lol
stack
overflow

代码

'''First I read the content of existing file and i append the first line of it to the text i want to appear in beginning'''
with open("text.txt", "r") as f:
    existing_lines = f.readlines()
    text_to_append = "Test"
    existing_lines[0] = text_to_append+"\n"+existing_lines[0]
'''And here I wite to the file'''
with open("text.txt", "w") as f:
    f.writelines(existing_lines)

Output:text.txt

Test
123
lol
stack
overflow

您可以在 text_to_append 中放置任何内容,只要它的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM