0

I have a text file name s1.txt and want to check if its open in python 3

    with open("s1.txt","r") as f:
        x = f.read()

I did saw the similar question on SO but its for python 2.0 Any help on the topic would be great

Mohit Narwani
  • 169
  • 2
  • 11
  • Does this answer your question? [How do I check which version of Python is running my script?](https://stackoverflow.com/questions/1093322/how-do-i-check-which-version-of-python-is-running-my-script) – Libra Dec 08 '22 at 19:20
  • @Libra that's not the question being asked. OP wants to know how to tell if a file is open, using Python 3. They know what version they're using... – MattDMo Dec 08 '22 at 19:21
  • @MattDMo Lol that makes more sense, the wording of the title confused me. "opened in" – Libra Dec 08 '22 at 19:22
  • Please specify your operating system, since you open the file for reading, other processed may read it too. – 576i Dec 08 '22 at 19:23
  • Are you asking about a specific file name, or if a file handler (`f` in your code) is open? – MattDMo Dec 08 '22 at 19:23
  • 3
    If you're inside the with block the file is open. What else do you want to check? – Sören Dec 08 '22 at 19:23
  • for all OS and yes for a file name s1.txt – Mohit Narwani Dec 08 '22 at 19:24
  • I'm still confused @MohitNarwani ...you want to how many places your text file is currently open? Like for example if file is opened in windows you to print file is opened in windows? through python – Bhargav - Retarded Skills Dec 08 '22 at 19:48
  • yes exactly Bhargav – Mohit Narwani Dec 08 '22 at 19:51
  • 1
    If you can add the link to the Python 2.0 question, it might make it easier for someone to find a Python 3.x solution. – sj95126 Dec 08 '22 at 19:53
  • What was the last version of Python where the file object didn't have a `closed` member? 6+ year old releases of 2.4.x have it. Basing things on the 22 year old 2.0 seems a bit odd. Given that this is likely valid for any version of Python released in the last decade, it shouldn't be focused on just 3.8.0 (if it should be asked at all -- there's really no duplicate?). – Dan Mašek Dec 08 '22 at 20:21

4 Answers4

2

f.closed should do the trick

For example

with open("myfile.txt","r") as f:
    x = f.read()
    is_file_open = not f.closed #returns true if file is open
    print(is_file_open)

This will not detect if the file is open by other processes!

If you want to check that then

import os 


def is_file_open(filename):
    try:
        os.rename(filename, filename)
        return False
    except:
        return True

print(is_file_open("myfile.txt")) # return true if file is open
Moosa
  • 31
  • 3
0

You can use closed

In your example.

with open("s1.txt","r") as f:
    x = f.read()
    print(not f.closed)  # True (it's open)
print(not f.closed)  # False (the file has been closed)
0x0fba
  • 1,520
  • 1
  • 1
  • 11
0

If you want o check if file is opened in windows through python you can try this dirty trick. If a file is used in another process which means if a file is opened in winodws we can't rename it.

import os

file = 's1.txt'
if os.path.exists(file):
    try:
        os.rename(file, file)
        print ('File is not opened in windows')
    except OSError as e:
        print ('File is opened in windows & being used by another program')

Warning: This thing only works in winodws

I'm also adding this answer not sure what is actual aim. If you want to check if file opened in same proccess python code then

with open("s1.txt","r") as f:
    x = f.read()

    if not f.closed:
        print("File is already opened in python")
0

The psutil library provides a method to discover running processes and check for open files in a given process.

If you want to check that a given process is being opened by a specific version of python (like 3.8.0) you can check that too by checking the version of the python executable using subprocess (there may be a cleaner way to do this)

import psutil
import subprocess
import os

python_version = '3.8.0'
my_file = 's1.txt'

# iterate over all processes
for proc in psutil.process_iter():
    # check if a process name contains the string 'python' (this is not foolproof since you can imagine a scenario where a python process is running under a different name but it's good enough for now)
    if 'python' in proc.name():
       # get the version of the running python process you found
       version = subprocess.run(['python', '-c', 'v = __import__("sys").version_info; print("{}.{}.{}".format(v.major, v.minor, v.micro))'], stdout=subprocess.PIPE, universal_newlines=True).stdout
       # check if the version matches the one you're looking for
       if version.strip() == python_version:
           # check if your file is one of the files opened by the process you found
           open_filenames = [f.path for f in proc.open_files()]
           if os.path.abspath(my_file) in open_filenames:
               print('file {} is open in python {} with PID {}'.format(my_file, python_version, proc.pid))

bunji
  • 5,063
  • 1
  • 17
  • 36