I run the following script:
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)
However, the cmd
variable gets written to the end of the file and not to the beginning (which I was expecting / hoping for). Can somebody explain to me why and how to prevent this, please?
I came up with an idea to do it this way, maybe you will find it useful.
Input: text.txt
123
lol
stack
overflow
Code
'''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
You can put anything in the text_to_append as long as its string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.