0

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 'sessionisfalse` 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

asked Apr 25, 2020 at 13:32

2 Answers 2

4

You need to close the file before deleting it. Use f.close() before os.remove(file_path) statement

answered Apr 25, 2020 at 13:41

Comments

1

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)
answered Apr 25, 2020 at 13:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.