Hướng dẫn how does python handle file not found exception? - python xử lý tệp không tìm thấy ngoại lệ như thế nào?

Tôi khá mới đối với Python.

Tôi đang cố gắng tạo một kịch bản sẽ đọc các giải pháp và răn đe Sudoku nếu chúng đúng hay không.

Những điều tôi cần:

1] Nhắc người dùng nhập một đường dẫn tệp/tệp bao gồm các số Sudoku. Tệp .TXT của nó gồm 9 hàng và cột. Chỉ bao gồm các con số.

2] Có một số loại xử lý lỗi.

3] Sau đó, nếu Sudoku hợp lệ, tôi nên tạo một tệp văn bản mới bằng cách sử dụng định dạng giống như tệp đầu vào gốc với tiền tố "đúng_"

Tôi chưa hoàn thành chương trình, nhưng tôi gặp lỗi này khi đặt một đường dẫn sai hoặc tên tệp.

 Hello to Sudoku valitator,

 Please type in the path to your file and press 'Enter': example.txt #This is a non existing file, to test the Error Exception
    'Traceback (most recent call last):
  File "C:/Users/FEDROS/Desktop/bs.py", line 9, in 
    sudoku = open(prompt, 'r').readlines()
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'

Đây là kịch bản của tôi:

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))

Cảm ơn, bất kỳ lời khuyên hoặc sự giúp đỡ sẽ được đánh giá cao.

Bởi Lenin Mishra ở Python - ngày 22 tháng 1 năm 2022

Học cách xử lý lỗi FILENOTFOUND trong Python bằng cách sử dụng khối Excet Try-Except.

Hướng dẫn how does python handle file not found exception? - python xử lý tệp không tìm thấy ngoại lệ như thế nào?
FILENOTFOUND Lỗi trong Python

Ngoại lệ

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
5 trong Python được nâng lên khi bạn đang cố gắng truy cập một tệp hoặc một thư mục không tồn tại.

ví dụ 1

Code/Output

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'

Bạn có thể xử lý các lỗi như vậy bằng cách sử dụng lớp ngoại lệ

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
5.


Ví dụ 2

Mã số

try:
    x = open('random.txt')
except FileNotFoundError as e:
    print(f"FileNotFoundError successfully handled\n"
          f"{e}")

Đầu ra

FileNotFoundError successfully handled
[Errno 2] No such file or directory: 'random.txt'
Mã trên sử dụng dây F. Kiểm tra rằng bài viết và các kỹ thuật định dạng chuỗi khác.

Kiểm tra các lớp ngoại lệ tích hợp Python khác trong Python.

Lớp học tích hợp-pylenin

Một lập trình viên nhằm mục đích dân chủ hóa giáo dục trong thế giới lập trình và giúp các đồng nghiệp của mình đạt được sự nghiệp trong mơ của họ.

Hướng dẫn how does python handle file not found exception? - python xử lý tệp không tìm thấy ngoại lệ như thế nào?

Hướng dẫn how does python handle file not found exception? - python xử lý tệp không tìm thấy ngoại lệ như thế nào?

Các tệp được xác định vị trí trên đĩa nơi lưu trữ dữ liệu liên quan. Làm việc với các tập tin sẽ làm cho các chương trình của bạn nhanh chóng khi phân tích khối lượng dữ liệu. Ngoại lệ là các đối tượng đặc biệt mà bất kỳ ngôn ngữ lập trình nào sử dụng để quản lý các lỗi xảy ra khi một chương trình đang chạy.

Trong hướng dẫn này, chúng tôi sẽ tìm hiểu về các hoạt động tệp trong Python. Các hoạt động này bao gồm đọc, viết và nối vào một tệp. Chúng tôi cũng sẽ tìm hiểu về việc xử lý ngoại lệ

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
7 và
while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
8.

Điều kiện tiên quyết

Có một số kiến ​​thức cơ bản về ngôn ngữ mã hóa Python.

Đọc từ một tập tin

Khi làm việc với dữ liệu từ tệp văn bản, trước tiên bạn phải đọc nó vào bộ nhớ. Để đọc một tập tin, bạn phải có một tệp tồn tại.

Hãy để tạo một tệp văn bản chứa danh sách các năm từ

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
9 đến
x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
0 bằng trình chỉnh sửa và lưu nó trong cùng một thư mục lưu trữ các tệp Python của chúng tôi là & nbsp; ________ 21.

Tệp & nbsp; ____ ____ 21 & nbsp; nên có văn bản sau:

Dưới đây là một chương trình mở tệp trên, đọc nó và in dữ liệu trong tệp:

with open('years.txt') as file_object:
    contents = file_object.read()
    print(contents)

Tên của tệp sẽ được mở được chuyển đến hàm

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
3 như đối số duy nhất của nó. Python tìm kiếm & nbsp; tệp ____ 21 & nbsp; trong thư mục, nơi lưu trữ tệp python của chúng tôi.

Hàm

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
3 trả về một đối tượng đại diện cho tệp (năm.txt) sau đó được lưu trữ trong biến file_object.

Từ khóa

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
6 đóng tệp khi truy cập vào nó không còn cần.

Phương pháp

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
7 được sử dụng để đọc toàn bộ dữ liệu trong tệp và lưu trữ nó theo nội dung.

Chúng tôi nhận được kết quả sau khi chúng tôi chạy mã trên:

Làm việc với nội dung của một tệp

Bây giờ, bạn đã học được cách đọc một tệp vào bộ nhớ, hãy để thử làm điều gì đó với dữ liệu đó.

Hãy cùng tạo ra một dòng duy nhất giữ tất cả các chữ số trong tệp & nbsp; ____ ____ 21 & nbsp; không có khoảng trắng trong đó như hiển thị bên dưới:

with open('years.txt') as file_object:
    lines = file_object.readlines()
yrs_string = '' # create a variable yrs_string to hold the digits of years
for line in lines: # create a loop that adds each line of digits to yrs_string
     yrs_string += line.rstrip() #.rstrip() removes the newline character from each line
print(yrs_string) # print this string
print(len(yrs_string)) # print how long the string is 
 # OUTPUT
 # 209020702089
 # 12

Lưu ý: Python xử lý tất cả văn bản trong một tệp văn bản dưới dạng chuỗi. Nếu bạn đọc một số từ một tệp và bạn muốn thực hiện các hoạt động số học, hãy chuyển đổi nó thành float bằng hàm

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
9 hoặc số nguyên bằng hàm
try:
    x = open('random.txt')
except FileNotFoundError as e:
    print(f"FileNotFoundError successfully handled\n"
          f"{e}")
0.

Ghi vào một tệp

Một trong những cách đơn giản nhất để lưu dữ liệu, là ghi vào một tệp. Đầu ra sẽ vẫn còn ngay cả sau khi chúng tôi đóng thiết bị đầu cuối có đầu ra của chương trình.

Khi viết văn bản vào một tệp, chúng tôi sử dụng hàm

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
3 với hai đối số - đối số đầu tiên là tên tệp, trong khi đối số thứ hai là chế độ bạn muốn mở tệp.

Có bốn chế độ trong đó bạn có thể mở một tệp:

  1. Chế độ đọc (‘R,)
  2. Chế độ viết (‘W,)
  3. Chế độ nối (‘A,)
  4. Đọc và viết (‘R+,)

Ghi vào một tệp trống

Nếu tệp bạn đang viết hoàn toàn không tồn tại, hàm

x = open("random_file.txt")

>>> FileNotFoundError: [Errno 2] No such file or directory: 'random_file.txt'
3 tự động tạo tệp.

Ví dụ:

with open('student.txt', 'w') as file_object:
    file_object.write("My name is Felix.")

Mã trên không in đầu ra trên thiết bị đầu cuối, nhưng khi bạn mở & nbsp; tệp ________ 33 & nbsp;, bạn sẽ thấy một dòng:

Lưu ý: Khi mở một tệp trong chế độ ‘W và tệp tồn tại, Python sẽ xóa tệp trước khi trả về đối tượng tệp.

Nối vào một tập tin

Để thêm dữ liệu vào một tệp, hãy mở nó trong & nbsp; chế độ nối. Bất kỳ dữ liệu bạn viết sẽ được đặt ở cuối tệp.

Hãy để thêm một số dòng trong & nbsp; ________ 33 & nbsp; tệp: tệp:

with open('student.txt', 'a') as file_object: #’a’ argument to open the file for appending
      file_object.write("I am 6 years old\n")
      file_object.write("I love playing games\n")

Tệp mới & nbsp; ________ 33 & nbsp; trông như thế này:

My name is Felix.
I am 6 years old
I love playing games

Ngoại lệ

Ngoại lệ là các đối tượng duy nhất mà Python sử dụng để kiểm soát các lỗi xảy ra khi một chương trình đang chạy. Các lỗi ngoại lệ phát sinh khi các chương trình Python cú pháp chính xác tạo ra lỗi.

Python tạo ra một đối tượng ngoại lệ bất cứ khi nào những sai lầm này xảy ra. Khi chúng tôi viết mã liên quan đến ngoại lệ, các chương trình của chúng tôi sẽ tiếp tục chạy, ngay cả khi một lỗi được ném. Nếu chúng tôi không có, các chương trình của chúng tôi sẽ ngừng thực hiện và hiển thị một dấu vết, điều này rất khó để người dùng hiểu.

Python sử dụng khối Try-Except-Finally để kiểm soát các ngoại lệ. Một khối Exccept thử thông báo cho Python cách hành động khi một ngoại lệ xuất hiện. Các chương trình của chúng tôi sẽ tiếp tục thực hiện ngay cả khi mọi thứ đi sai.

Xử lý ngoại lệ ZerodivisionError

Hãy cùng chạy một chương trình phân chia một số cho 0. Chúng tôi biết đó là không thực tế, nhưng hãy để Lừa xem Python làm gì:

Khi chúng tôi chạy mã Python trên, hãy đưa ra dấu vết sau:

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
0

Vì Python không thể chia số cho 0, nên nó báo cáo một lỗi trong dấu vết AS & NBSP; ZerodivisionError, đây là một đối tượng ngoại lệ. Loại đối tượng này phản ứng với một kịch bản mà Python có thể làm những gì chúng tôi đã yêu cầu.

Nếu bạn nghĩ rằng một lỗi có thể xảy ra, hãy sử dụng khối Excet thử để kiểm soát ngoại lệ có thể được nêu ra.

Để xử lý ngoại lệ

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
7, hãy sử dụng khối Excet Try-Except như thế này:

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
1

Xử lý ngoại lệ FilenotFounderror

Lỗi sẽ luôn phát sinh khi làm việc với các tệp bị thiếu. Python có thể không truy xuất một tệp, nếu bạn đã viết sai cách viết của tên tệp hoặc tệp không tồn tại.

Chúng tôi xử lý tình huống này bằng cách áp dụng khối Excet Try-Except.

Ví dụ: chương trình bên dưới cố gắng đọc một tệp không tồn tại trên máy tính của tôi:

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
2

Vì Python không thể đọc một tệp không tồn tại, nên nó làm tăng một ngoại lệ:

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
3

Vì Python không thể tìm thấy tệp, chúng tôi đang mở nó tạo ra một ngoại lệ đó là & nbsp; filenotfounderror & nbsp; ngoại lệ.

Trong ví dụ này, chức năng & nbsp; open () & nbsp; tạo ra lỗi. Để giải quyết lỗi này, hãy sử dụng khối thử ngay trước dòng, liên quan đến & nbsp; open () & nbsp; function:open() function creates the error. To solve this error, use the try block just before the line, which involves the open() function:

while True:
    try:
        prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
        break
    except (FileNotFoundError, IOError):
        print("Wrong file or file path")

sudoku = open(prompt, 'r').readlines()

def check(game):
    n = len(game)
    if n < (1):
        return False

    for i in range(0, n):
        horizontal = []
        vertical = []
        for k in range(0, n):

            if game[k][i] in vertical:
                return ("File checked for errors. Your options are wrong!")
            vertical.append(game[k][i])

            if game[i][k] in horizontal:
                return ("File checked for errors. Your options are wrong!")
            horizontal.append(game[i][k])
    return ("File checked for errors. Your options are correct!")

print (check(sudoku))
4

Sự kết luận

Trong bài viết này, chúng tôi đã học được cách:

  • Đọc từ một tệp
  • Làm việc với một nội dung tệp
  • Ghi vào một tệp
  • Xử lý ngoại lệ ZerodivisionError
  • Xử lý ngoại lệ FilenotFounderror

đọc thêm

Để biết thêm thông tin về các tệp và ngoại lệ trong Python, hãy xem các liên kết bên dưới:

  • Xử lý ngoại lệ trong Python
  • Các tập tin Python
  • Tập tin và ngoại lệ

Đóng góp đánh giá ngang hàng của: Srishilesh P S

Làm thế nào để Python xử lý ngoại lệ tệp?

Trong Python, các trường hợp ngoại lệ có thể được xử lý bằng cách sử dụng câu lệnh thử. Hoạt động quan trọng có thể tăng một ngoại lệ được đặt bên trong mệnh đề thử. Mã xử lý các ngoại lệ được viết trong mệnh đề ngoại trừ. Do đó, chúng tôi có thể chọn những hoạt động để thực hiện một khi chúng tôi đã bắt được ngoại lệ.using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

Làm thế nào để Python xử lý Oserror?

Xử lý lỗi Oserrors thường có thể được ngăn chặn bằng cách đảm bảo sự tồn tại của các tệp và thư mục đang được truy cập.Oserror, giống như tất cả các lỗi khác, có thể được xử lý bằng cách sử dụng các khối Except.using try-except blocks.