I am working on a project where I have many json files stored in a directory. I need to read all the files and check there data. If 'sessionis
false` in any of the files, I need to delete the file. Below is the code:
files = os.listdir(config_files_path)
for file in files:
file_path = config_files_path + '//' + file
f = open(file_path)
data = json.load(f)
if not data['session']:
# delete this file
os.remove(file_path)
In the above code, I am getting the list of all the files. Then iterating over each file and reading its content in data
. if not data['session']
, I need to delete that file. But doing so I am getting process cannot access the file as its being used by another process
. Is there any way we can delete the file. Please help. Thanks
2 Answers 2
You need to close the file before deleting it. Use f.close() before os.remove(file_path) statement
Comments
The error is raised because the file is still open. You must close it before trying to delete it. So, after you have loaded the data, do f.close()
. Like this:
files = os.listdir(config_files_path)
for file in files:
file_path = config_files_path + '//' + file
f = open(file_path)
data = json.load(f)
f.close() # <-- close the file
if not data['session']:
# delete this file
os.remove(file_path)