[英]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.