How do I close a file opened using os.startfile(), Python 3.6

Question:

I want to close some files like .txt, .csv, .xlsx that I have opened using os.startfile().

I know this question asked earlier but I did not find any useful script for this.

I use windows 10 Environment

Asked By: Learnings

||

Answers:

Based on this SO post, there’s no way to close the file being opened with os.startfile(). Similar things are discussed in this Quora post.

However, as is suggested in the Quora post, using a different tool to open your file, such as subprocess or open(), would grant you greater control to handle your file.

I assume you’re trying to read in data, so in regards to your comment about not wanting to close the file manually, you could always use a with statement, e.g.

with open('foo') as f:
    foo = f.read()

Slightly cumbersome, as you would have to also do a read(), but it may suit your needs better.

Answered By: natn2323

I believe the question wording is a bit misleading – in reality you want to close the app you opend with the os.startfile(file_name)

Unfortunately, os.startfile does not give you any handle to the returned process.
help(os.startfile)

startfile returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way
to retrieve the application’s exit status.

Luckily, you have an alternative way of opening a file via a shell:

shell_process = subprocess.Popen([file_name],shell=True) 
print(shell_process.pid)

Returned pid is the pid of the parent shell, not of your process itself.
Killing it won’t be sufficient – it will only kill a shell, not the child process.
We need to get to the child:

parent = psutil.Process(shell_process.pid)
children = parent.children(recursive=True)
print(children)
child_pid = children[0].pid
print(child_pid)

This is the pid you want to close.
Now we can terminate the process:

os.kill(child_pid, signal.SIGTERM)
# or
subprocess.check_output("Taskkill /PID %d /F" % child_pid)

Note that this is a bit more convoluted on windows – there is no os.killpg
More info on that: How to terminate a python subprocess launched with shell=True

Also, I received PermissionError: [WinError 5] Access is denied when trying to kill the shell process itself with os.kill

os.kill(shell_process.pid, signal.SIGTERM)

subprocess.check_output("Taskkill /PID %d /F" % child_pid) worked for any process for me without permision error
See WindowsError: [Error 5] Access is denied

Answered By: Lesiak

In order to properly get the pid of children,you may add a while cycle


import subprocess
import psutil
import os
import time
import signal
shell_process = subprocess.Popen([r'C:Pt_Pythondata1.mp4'],shell=True)
parent = psutil.Process(shell_process.pid)
while(parent.children() == []):
    continue
children = parent.children()
print(children)
Answered By: namespace-Pt

os.startfile()
helps to launch the application but has no option to exit, kill or close the launched application.

The other alternative would be using subprocesses this way:

import subprocess
import time

# File (a CAD in this case) and Program (desired CAD software in this case) # r: raw strings
file = r"F:Pradnil KambleGetThisOpen.3dm"
prog = r"C:Program FilesRhinoRhino.exe"

# Open file with desired program 
OpenIt = subprocess.Popen([prog, file])

# keep it open for 30 seconds
time.sleep(30)

# close the file and the program 
OpenIt.terminate() 
Answered By: Pradnil Kamble

os.system('taskkill /f /im Rainmeter.exe') work for me

in my case, i use the os.startfile("C:\Program Files\Rainmeter\Rainmeter.exe") command to open Rainmeter.exe
replace file and path with yours

Answered By: Muhammad Salman

for excel files , that have been alredy been opened with any mechanism

# function to close a workbook given name
def close_wb(wbname):
    import xlwings as xw    
    try: 
        app = xw.apps.active # get the active Excel application
        print ('closing workbook',wbname)
        # make workbook with given name active
        wb = app.books[wbname]
        wb.close()
    except: pass
Answered By: user15420598
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.