Hướng dẫn how do you check if file is already open in python? - làm cách nào để kiểm tra xem tệp đã được mở trong python chưa?

Và tôi muốn đạt được điều đó cụ thể với cấu trúc thử.

Câu hỏi liên quan này cho thấy tôi có thể làm:

try:
    open[fileName, 'wb+']
except:
    print["File already opened!"]
    raise

Tuy nhiên, nó không hoạt động với tôi. Tôi có thể mở cùng một tệp nhiều lần mà không có bất kỳ vấn đề nào:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']

Có phải vì tôi có Python 3,5? Hay vì tôi đang sử dụng Raspbian?

Cảm ơn đã giúp đỡ!

Khi được hỏi ngày 29 tháng 5 năm 2016 lúc 22:28May 29, 2016 at 22:28

Maxime Duprémaxime DupréMaxime Dupré

5.1597 Huy hiệu vàng36 Huy hiệu bạc66 Huy hiệu Đồng7 gold badges36 silver badges66 bronze badges

13

Bạn nên mở cùng một tệp nhưng gán chúng cho các biến khác nhau, như vậy:

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
9 chỉ kiểm tra xem tệp đã được mở bởi cùng một quy trình Python.

Shaido

26.6K21 Huy hiệu vàng69 Huy hiệu bạc72 Huy hiệu đồng21 gold badges69 silver badges72 bronze badges

Đã trả lời ngày 29 tháng 5 năm 2016 lúc 23:05May 29, 2016 at 23:05

Atakanyenelatakanyenelatakanyenel

1.3471 Huy hiệu vàng15 Huy hiệu bạc20 Huy hiệu Đồng1 gold badge15 silver badges20 bronze badges

3

Tôi sẽ đề nghị sử dụng một cái gì đó như thế này

# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError

Được chỉnh sửa để phù hợp với các vấn đề cụ thể của OP

class FileObject[object]:
    def __init__[self, file_name]:
        self.file_name = file_name
        self.__file = None
        self.__locked = False

    @property
    def file[self]:
        return self.__file

    @property
    def locked[self]:
        return self.__locked

    def open[self, mode, lock=True]:#any testing on file should go before the if statement such as os.path.exists[]
        #replace mode with *args if you want to pass multiple modes
        if not self.locked:
            self.__locked = lock
            self.__file = open[self.file_name, mode]
            return self.file
        else:
            print 'Cannot open file because it has an exclusive lock placed on it'
            return None #do whatever you want to do if the file is already open here

    def close[self]:
        if self.file != None:
            self.__file.close[]
            self.__file = None
            self.__locked = False

    def unlock[self]:
        if self.file != None:
            self.__locked = False

Đã trả lời ngày 29 tháng 5 năm 2016 lúc 23:09May 29, 2016 at 23:09

ThelazyscripterthelazyscripterTheLazyScripter

2.5011 huy hiệu vàng9 Huy hiệu bạc19 Huy hiệu đồng1 gold badge9 silver badges19 bronze badges

7

Bạn có thấy hướng dẫn này hữu ích không?: in this tutorial, you’ll learn how to check if a file exists.

Làm thế nào bạn có thể kiểm tra xem một tệp có được mở thành công hay không giải thích?

Kiểm tra để đảm bảo tệp đã được mở thành công bằng cách kiểm tra xem có biến == null không. Nếu có, một lỗi đã xảy ra. Sử dụng các hàm FPRINTF hoặc FSCANF để ghi/đọc từ tệp. Thông thường các cuộc gọi chức năng này được đặt trong một vòng lặp.

Làm thế nào tôi có thể biết nếu một tệp đã được mở trong một chương trình khác?

from os.path import exists file_exists = exists[path_to_file]

Code language: JavaScript [javascript]

Xác định chương trình nào đang sử dụng một tập tin.

from pathlib import Path path = Path[path_to_file] path.is_file[]

Code language: JavaScript [javascript]

Mở quy trình Explorer. Chạy với tư cách là quản trị viên ..

Trên thanh công cụ, tìm biểu tượng Gunsight ở bên phải ..

Kéo biểu tượng và thả nó vào tệp mở hoặc thư mục bị khóa ..

import os.path

Code language: JavaScript [javascript]

Việc thực thi đang sử dụng tệp sẽ được tô sáng trong Danh sách hiển thị chính của Process Explorer ..

Làm thế nào tôi có thể biết nếu một tệp đang được sử dụng?

Cách quản lý chung để kiểm tra xem một tệp đang được sử dụng là mở tệp trong một khối thử. Nếu tệp đang được sử dụng, nó sẽ ném IOException. Một cách khác để kiểm tra xem một tệp đang được sử dụng là gọi API CreatFile. Nếu một tệp đang được sử dụng, việc trả về tay cầm không hợp lệ.

Tóm tắt: Trong hướng dẫn này, bạn sẽ học cách kiểm tra xem một tệp có tồn tại không.

Tuy nhiên, nó không phải là trường hợp, bạn cần vượt qua đường dẫn tệp đầy đủ của tệp. Ví dụ:

/path/to/filename

Ngay cả khi bạn chạy chương trình trên Windows, bạn nên sử dụng Slash phía trước [

# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
3] để tách đường dẫn. Nó sẽ hoạt động trên các Windows, MacOS và Linux.

Ví dụ sau sử dụng chức năng

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
0 để kiểm tra xem tệp
# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
5 có tồn tại trong cùng thư mục với chương trình không:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
0

Nếu tệp

# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
5 tồn tại, bạn sẽ thấy đầu ra sau:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
1

Nếu không, bạn sẽ thấy

# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
1 trên màn hình:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
2

Để thực hiện cuộc gọi đến chức năng

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
0 ngắn hơn và rõ ràng hơn, bạn có thể nhập chức năng đó và đổi tên thành hàm
# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
9 như thế này:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
3

2] Sử dụng mô -đun Pathlib để kiểm tra xem tệp có tồn tại không

Python đã giới thiệu mô -đun

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
4 kể từ phiên bản 3.4.

Mô-đun

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
4 cho phép bạn thao tác các tệp và thư mục bằng cách sử dụng phương pháp hướng đối tượng. Nếu bạn không quen thuộc với lập trình hướng đối tượng, hãy xem phần Python OOP.

Đầu tiên, nhập lớp

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
3 từ mô -đun
file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
4:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
4

Sau đó, khởi tạo một thể hiện mới của lớp

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
3 và khởi tạo nó với đường dẫn tệp mà bạn muốn kiểm tra sự tồn tại:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
5

Cuối cùng, hãy kiểm tra xem tệp có tồn tại bằng phương pháp

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
2 không:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
6

Nếu tệp không tồn tại, phương thức

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
2 trả về
# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
1. Nếu không, nó trả về
# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
0.

Ví dụ sau đây cho thấy cách sử dụng lớp

file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
3 từ mô -đun
file_obj = open[filename, "wb+"]

if not file_obj.closed:
    print["File is already opened"]
4 để kiểm tra xem tệp
# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
5 có tồn tại trong cùng một thư mục của chương trình không:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
7

Nếu tệp

# Only works on Windows
def is_open[file_name]:
    if os.path.exists[file_name]:
        try:
            os.rename[file_name, file_name] #can't rename an open file so an error will be thrown
            return False
        except:
            return True
    raise NameError
5 tồn tại, bạn sẽ thấy đầu ra sau:

fileObj1 = open[fileName, 'wb+']
fileObj2 = open[fileName, 'wb+']
8

Bản tóm tắt

  • Sử dụng chức năng

    from os.path import exists file_exists = exists[path_to_file]

    Code language: JavaScript [javascript]
    3 hoặc phương thức

    from os.path import exists file_exists = exists[path_to_file]

    Code language: JavaScript [javascript]
    4 để kiểm tra xem tệp có tồn tại không

Bạn có thấy hướng dẫn này hữu ích không?

Làm thế nào bạn có thể kiểm tra xem một tệp có được mở thành công hay không giải thích?

Kiểm tra để đảm bảo tệp đã được mở thành công bằng cách kiểm tra xem có biến == null không. Nếu có, một lỗi đã xảy ra. Sử dụng các hàm FPRINTF hoặc FSCANF để ghi/đọc từ tệp. Thông thường các cuộc gọi chức năng này được đặt trong một vòng lặp.checking to see if the variable == NULL. If it does, an error has occured. Use the fprintf or fscanf functions to write/read from the file. Usually these function calls are placed in a loop.

Làm thế nào tôi có thể biết nếu một tệp đã được mở trong một chương trình khác?

Xác định chương trình nào đang sử dụng một tập tin..
Mở quy trình Explorer.Chạy với tư cách là quản trị viên ..
Trên thanh công cụ, tìm biểu tượng Gunsight ở bên phải ..
Kéo biểu tượng và thả nó vào tệp mở hoặc thư mục bị khóa ..
Việc thực thi đang sử dụng tệp sẽ được tô sáng trong Danh sách hiển thị chính của Process Explorer ..

Làm thế nào tôi có thể biết nếu một tệp đang được sử dụng?

Cách quản lý chung để kiểm tra xem một tệp đang được sử dụng là mở tệp trong một khối thử.Nếu tệp đang được sử dụng, nó sẽ ném IOException.Một cách khác để kiểm tra xem một tệp đang được sử dụng là gọi API CreatFile.Nếu một tệp đang được sử dụng, việc trả về tay cầm không hợp lệ.open the file in a try block. If the file is in use, it will throw an IOException. Another way to check whether a file is in use is to call the CreateFile API. If a file is in use, the handle return is invalid.

Bài Viết Liên Quan

Chủ Đề