最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現檢測文件是否存在的方法完整指南

 更新時間:2025年09月22日 09:03:42   作者:Python×CATIA工業(yè)智造  
Python作為一門強大的編程語言,提供了多種方法來檢測文件存在性,本文將深入探討Python中文件存在性檢測的各種方法,大家可以根據需要進行選擇

引言

在軟件開發(fā)中,文件操作是最常見且基礎的任務之一。無論是讀取配置文件、處理用戶上傳、管理日志文件,還是進行數據持久化,我們都需要在操作文件前確認其是否存在。看似簡單的"檢查文件是否存在"操作,實際上涉及操作系統交互、異常處理、競爭條件、性能考量等多個復雜方面。

Python作為一門強大的編程語言,提供了多種方法來檢測文件存在性。從簡單的os.path.exists()到更健壯的異常處理模式,每種方法都有其適用場景和優(yōu)缺點。選擇不當的方法可能導致程序出現競爭條件、性能問題甚至安全漏洞。

本文將深入探討Python中文件存在性檢測的各種方法,分析其原理和適用場景,并提供大量實際應用示例。我們不僅會介紹基礎用法,還會深入討論高級話題如競爭條件處理、性能優(yōu)化、安全考量等,幫助讀者在不同場景下選擇最合適的解決方案。

一、基礎檢測方法

1.1 使用os.path模塊

os.path模塊提供了最直接的文件存在性檢測方法,適用于大多數簡單場景。

import os
import os.path

def check_file_existence_basic(file_path):
    """
    基礎文件存在性檢測
    """
    # 檢查文件是否存在
    if os.path.exists(file_path):
        print(f"文件 {file_path} 存在")
        
        # 進一步檢查是否是文件(不是目錄)
        if os.path.isfile(file_path):
            print("這是一個文件")
            return True
        else:
            print("這不是一個普通文件(可能是目錄)")
            return False
    else:
        print(f"文件 {file_path} 不存在")
        return False

# 使用示例
file_path = "example.txt"
result = check_file_existence_basic(file_path)

1.2 區(qū)分文件類型

在實際應用中,我們經常需要區(qū)分文件、目錄和其他類型的文件系統對象。

import os
import stat

def analyze_path_type(path):
    """
    詳細分析路徑類型
    """
    if not os.path.exists(path):
        print(f"路徑 {path} 不存在")
        return False
    
    # 檢查文件類型
    if os.path.isfile(path):
        print(f"{path} 是普通文件")
        
    if os.path.isdir(path):
        print(f"{path} 是目錄")
        
    if os.path.islink(path):
        print(f"{path} 是符號鏈接")
        # 解析符號鏈接指向的實際路徑
        real_path = os.path.realpath(path)
        print(f"指向: {real_path}")
        
    # 檢查文件權限
    if os.access(path, os.R_OK):
        print("當前用戶有讀取權限")
    if os.access(path, os.W_OK):
        print("當前用戶有寫入權限")
    if os.access(path, os.X_OK):
        print("當前用戶有執(zhí)行權限")
    
    return True

# 使用示例
analyze_path_type("/etc/passwd")

二、高級檢測方法與模式

2.1 EAFP vs LBYL風格

Python社區(qū)有兩種主要的錯誤處理風格:EAFP(Easier to Ask for Forgiveness than Permission)和LBYL(Look Before You Leap)。

import os

def check_file_eafp(file_path):
    """
    EAFP風格:直接嘗試操作,捕獲異常
    """
    try:
        with open(file_path, 'r') as f:
            content = f.read()
        print("文件存在且可讀取")
        return True, content
    except FileNotFoundError:
        print("文件不存在")
        return False, None
    except PermissionError:
        print("沒有讀取權限")
        return False, None
    except IOError as e:
        print(f"讀取文件時發(fā)生錯誤: {e}")
        return False, None

def check_file_lbyl(file_path):
    """
    LBYL風格:先檢查再操作
    """
    if not os.path.exists(file_path):
        print("文件不存在")
        return False, None
        
    if not os.path.isfile(file_path):
        print("路徑不是文件")
        return False, None
        
    if not os.access(file_path, os.R_OK):
        print("沒有讀取權限")
        return False, None
        
    try:
        with open(file_path, 'r') as f:
            content = f.read()
        return True, content
    except IOError as e:
        print(f"讀取文件時發(fā)生錯誤: {e}")
        return False, None

# 使用示例
file_path = "config.ini"

# EAFP方式
exists_eafp, content_eafp = check_file_eafp(file_path)

# LBYL方式
exists_lbyl, content_lbyl = check_file_lbyl(file_path)

2.2 使用pathlib模塊(Python 3.4+)

pathlib模塊提供了面向對象的路徑操作方式,是現代Python代碼的首選。

from pathlib import Path

def check_file_pathlib(file_path):
    """
    使用pathlib檢測文件存在性
    """
    path = Path(file_path)
    
    if path.exists():
        print(f"路徑 {path} 存在")
        
        if path.is_file():
            print("這是一個文件")
            # 獲取文件信息
            print(f"文件大小: {path.stat().st_size} 字節(jié)")
            print(f"最后修改時間: {path.stat().st_mtime}")
            return True
        elif path.is_dir():
            print("這是一個目錄")
            return False
        elif path.is_symlink():
            print("這是一個符號鏈接")
            return False
    else:
        print(f"路徑 {path} 不存在")
        return False

# 使用示例
check_file_pathlib("example.txt")

三、處理競爭條件

3.1 競爭條件問題

在多進程、多線程或分布式環(huán)境中,文件狀態(tài)可能在檢查和使用之間發(fā)生變化,這就是著名的競爭條件問題。

import os
from threading import Thread
import time

def competitive_check_demo():
    """
    演示競爭條件問題
    """
    test_file = "temp_file.txt"
    
    # 刪除可能存在的舊文件
    if os.path.exists(test_file):
        os.remove(test_file)
    
    def create_file_later():
        """稍后創(chuàng)建文件"""
        time.sleep(0.1)  # 短暫延遲
        with open(test_file, 'w') as f:
            f.write("測試內容")
    
    # 啟動線程創(chuàng)建文件
    thread = Thread(target=create_file_later)
    thread.start()
    
    # 檢查文件是否存在
    if os.path.exists(test_file):
        print("文件存在,嘗試讀取...")
        # 這里可能出現競爭條件:文件可能在被檢查后立即被刪除
        try:
            with open(test_file, 'r') as f:
                content = f.read()
            print("成功讀取文件")
        except FileNotFoundError:
            print("文件在檢查后消失了!")
    else:
        print("文件不存在")
    
    thread.join()
    # 清理
    if os.path.exists(test_file):
        os.remove(test_file)

# 運行演示
competitive_check_demo()

3.2 解決競爭條件的方法

import os
import tempfile

def safe_file_operation(file_path, operation_func, *args, **kwargs):
    """
    安全的文件操作函數,處理競爭條件
    """
    max_retries = 3
    retry_delay = 0.1  # 100毫秒
    
    for attempt in range(max_retries):
        try:
            # 嘗試執(zhí)行操作
            return operation_func(file_path, *args, **kwargs)
        except FileNotFoundError:
            if attempt == max_retries - 1:
                raise
            time.sleep(retry_delay)
        except PermissionError:
            if attempt == max_retries - 1:
                raise
            time.sleep(retry_delay)
        except IOError as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(retry_delay)

def read_file_safely(file_path):
    """安全讀取文件"""
    with open(file_path, 'r') as f:
        return f.read()

# 使用示例
try:
    content = safe_file_operation("important_file.txt", read_file_safely)
    print("成功讀取文件內容")
except FileNotFoundError:
    print("文件不存在")
except Exception as e:
    print(f"讀取文件時發(fā)生錯誤: {e}")

四、實際應用場景

4.1 配置文件處理

from pathlib import Path
import json
import yaml

class ConfigManager:
    """
    配置文件管理器,處理多種配置格式
    """
    
    def __init__(self, config_paths=None):
        self.config_paths = config_paths or [
            "./config.json",
            "./config.yaml",
            "./config.yml",
            "~/app_config.json",
            "/etc/app/config.json"
        ]
    
    def find_config_file(self):
        """
        查找存在的配置文件
        """
        for config_path in self.config_paths:
            path = Path(config_path).expanduser()  # 處理~擴展
            
            if path.exists() and path.is_file() and os.access(path, os.R_OK):
                print(f"找到配置文件: {path}")
                return path
        
        print("未找到任何配置文件")
        return None
    
    def load_config(self):
        """
        加載配置文件
        """
        config_path = self.find_config_file()
        if not config_path:
            return None
        
        try:
            if config_path.suffix == '.json':
                with open(config_path, 'r') as f:
                    return json.load(f)
            elif config_path.suffix in ['.yaml', '.yml']:
                with open(config_path, 'r') as f:
                    return yaml.safe_load(f)
            else:
                print(f"不支持的配置文件格式: {config_path.suffix}")
                return None
        except Exception as e:
            print(f"加載配置文件時發(fā)生錯誤: {e}")
            return None

# 使用示例
config_manager = ConfigManager()
config = config_manager.load_config()
if config:
    print("配置加載成功")
else:
    print("使用默認配置")

4.2 日志文件輪轉檢查

import os
import time
from datetime import datetime
from pathlib import Path

class LogManager:
    """
    日志文件管理器,支持文件存在性檢查和輪轉
    """
    
    def __init__(self, log_dir="./logs", max_file_size=10 * 1024 * 1024):  # 10MB
        self.log_dir = Path(log_dir)
        self.max_file_size = max_file_size
        self.current_log_file = None
        
        # 確保日志目錄存在
        self.log_dir.mkdir(exist_ok=True)
    
    def get_current_log_file(self):
        """
        獲取當前日志文件路徑,必要時創(chuàng)建新文件
        """
        if self.current_log_file and self._should_rotate_log():
            self._rotate_log_file()
        
        if not self.current_log_file:
            self.current_log_file = self.log_dir / f"app_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
            
        return self.current_log_file
    
    def _should_rotate_log(self):
        """
        檢查是否需要日志輪轉
        """
        if not self.current_log_file.exists():
            return False
        
        try:
            return self.current_log_file.stat().st_size >= self.max_file_size
        except OSError:
            return True
    
    def _rotate_log_file(self):
        """
        執(zhí)行日志輪轉
        """
        if self.current_log_file and self.current_log_file.exists():
            # 重命名舊日志文件
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            archived_file = self.log_dir / f"app_{timestamp}.log"
            
            try:
                self.current_log_file.rename(archived_file)
                print(f"已輪轉日志文件: {archived_file}")
            except OSError as e:
                print(f"日志輪轉失敗: {e}")
        
        self.current_log_file = None
    
    def write_log(self, message):
        """
        寫入日志消息
        """
        log_file = self.get_current_log_file()
        
        try:
            with open(log_file, 'a') as f:
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                f.write(f"[{timestamp}] {message}\n")
        except OSError as e:
            print(f"寫入日志失敗: {e}")

# 使用示例
log_manager = LogManager()
for i in range(1000):
    log_manager.write_log(f"測試日志消息 {i}")

4.3 文件上傳處理

from pathlib import Path
import hashlib
import uuid
from typing import Optional

class FileUploadHandler:
    """
    文件上傳處理器,包含存在性檢查和沖突解決
    """
    
    def __init__(self, upload_dir: str = "./uploads"):
        self.upload_dir = Path(upload_dir)
        self.upload_dir.mkdir(exist_ok=True)
    
    def generate_unique_filename(self, original_filename: str) -> Path:
        """
        生成唯一的文件名,避免沖突
        """
        extension = Path(original_filename).suffix
        unique_id = uuid.uuid4().hex
        return self.upload_dir / f"{unique_id}{extension}"
    
    def file_exists_by_content(self, file_content: bytes) -> Optional[Path]:
        """
        通過內容哈希檢查文件是否已存在
        """
        content_hash = hashlib.sha256(file_content).hexdigest()
        
        # 檢查是否已有相同內容的文件
        for existing_file in self.upload_dir.iterdir():
            if existing_file.is_file():
                try:
                    with open(existing_file, 'rb') as f:
                        existing_content = f.read()
                    existing_hash = hashlib.sha256(existing_content).hexdigest()
                    
                    if existing_hash == content_hash:
                        return existing_file
                except IOError:
                    continue
        
        return None
    
    def safe_upload_file(self, file_content: bytes, original_filename: str) -> Path:
        """
        安全地上傳文件,處理各種邊界情況
        """
        # 檢查是否已存在相同內容的文件
        existing_file = self.file_exists_by_content(file_content)
        if existing_file:
            print(f"文件已存在,內容與 {existing_file} 相同")
            return existing_file
        
        # 生成唯一文件名
        target_path = self.generate_unique_filename(original_filename)
        
        # 確保目標文件不存在(盡管概率極低)
        if target_path.exists():
            # 如果發(fā)生沖突,重新生成文件名
            target_path = self.generate_unique_filename(original_filename)
        
        # 寫入文件
        try:
            with open(target_path, 'wb') as f:
                f.write(file_content)
            
            # 再次驗證文件寫入成功
            if not target_path.exists():
                raise IOError("文件寫入后驗證失敗")
            
            print(f"文件上傳成功: {target_path}")
            return target_path
            
        except IOError as e:
            print(f"文件上傳失敗: {e}")
            # 清理可能部分寫入的文件
            if target_path.exists():
                try:
                    target_path.unlink()
                except IOError:
                    pass
            raise

# 使用示例
upload_handler = FileUploadHandler()

# 模擬文件上傳
test_content = b"This is test file content"
try:
    saved_path = upload_handler.safe_upload_file(test_content, "test.txt")
    print(f"文件保存路徑: {saved_path}")
except Exception as e:
    print(f"上傳失敗: {e}")

五、性能優(yōu)化與最佳實踐

5.1 批量文件檢查優(yōu)化

import os
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import time

class BatchFileChecker:
    """
    批量文件檢查器,優(yōu)化大量文件存在性檢查的性能
    """
    
    def __init__(self, max_workers=None):
        self.max_workers = max_workers or os.cpu_count() or 4
    
    def check_files_sequential(self, file_paths):
        """
        順序檢查文件列表
        """
        results = {}
        for file_path in file_paths:
            path = Path(file_path)
            results[file_path] = path.exists()
        return results
    
    def check_files_parallel(self, file_paths):
        """
        并行檢查文件列表
        """
        results = {}
        
        def check_file(path):
            return path, Path(path).exists()
        
        with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
            future_results = executor.map(check_file, file_paths)
            for path, exists in future_results:
                results[path] = exists
        
        return results
    
    def benchmark_checkers(self, file_paths):
        """
        性能基準測試
        """
        # 順序檢查
        start_time = time.time()
        seq_results = self.check_files_sequential(file_paths)
        seq_duration = time.time() - start_time
        
        # 并行檢查
        start_time = time.time()
        par_results = self.check_files_parallel(file_paths)
        par_duration = time.time() - start_time
        
        print(f"順序檢查耗時: {seq_duration:.4f}秒")
        print(f"并行檢查耗時: {par_duration:.4f}秒")
        print(f"性能提升: {seq_duration/par_duration:.2f}倍")
        
        # 驗證結果一致性
        assert seq_results == par_results, "檢查結果不一致"
        
        return seq_results

# 使用示例
# 生成測試文件列表
test_files = [f"test_file_{i}.txt" for i in range(100)]

# 創(chuàng)建一些測試文件
for i in range(10):  # 創(chuàng)建前10個文件
    with open(f"test_file_{i}.txt", 'w') as f:
        f.write("test")

checker = BatchFileChecker()
results = checker.benchmark_checkers(test_files)

# 清理測試文件
for i in range(10):
    try:
        os.remove(f"test_file_{i}.txt")
    except OSError:
        pass

5.2 緩存文件狀態(tài)

from pathlib import Path
import time
from functools import lru_cache

class CachedFileChecker:
    """
    帶緩存的文件檢查器,減少重復檢查的開銷
    """
    
    def __init__(self, cache_ttl=5):  # 默認緩存5秒
        self.cache_ttl = cache_ttl
        self.cache = {}
    
    @lru_cache(maxsize=1024)
    def check_file_cached(self, file_path):
        """
        帶緩存的文件檢查
        """
        current_time = time.time()
        
        # 檢查緩存是否有效
        if file_path in self.cache:
            cached_time, exists = self.cache[file_path]
            if current_time - cached_time < self.cache_ttl:
                return exists
        
        # 實際檢查文件
        exists = Path(file_path).exists()
        self.cache[file_path] = (current_time, exists)
        
        return exists
    
    def clear_cache(self):
        """清空緩存"""
        self.cache.clear()
        self.check_file_cached.cache_clear()

# 使用示例
cached_checker = CachedFileChecker(cache_ttl=2)  # 2秒緩存

# 第一次檢查
print("第一次檢查:", cached_checker.check_file_cached("example.txt"))

# 立即再次檢查(使用緩存)
print("第二次檢查:", cached_checker.check_file_cached("example.txt"))

# 等待緩存過期
time.sleep(3)
print("緩存過期后檢查:", cached_checker.check_file_cached("example.txt"))

六、錯誤處理與日志記錄

6.1 健壯的文件檢查框架

import os
import logging
from pathlib import Path
from typing import Optional, Dict, Any

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class RobustFileChecker:
    """
    健壯的文件檢查器,包含完整的錯誤處理和日志記錄
    """
    
    def __init__(self, retry_attempts: int = 3, retry_delay: float = 0.1):
        self.retry_attempts = retry_attempts
        self.retry_delay = retry_delay
    
    def safe_check_exists(self, file_path: str) -> Optional[bool]:
        """
        安全地檢查文件是否存在,包含重試機制
        """
        for attempt in range(self.retry_attempts):
            try:
                exists = Path(file_path).exists()
                logger.debug(f"文件檢查成功: {file_path} -> {exists}")
                return exists
                
            except OSError as e:
                logger.warning(
                    f"文件檢查失敗 (嘗試 {attempt + 1}/{self.retry_attempts}): "
                    f"{file_path} - {e}"
                )
                
                if attempt == self.retry_attempts - 1:
                    logger.error(f"文件檢查最終失敗: {file_path}")
                    return None
                
                time.sleep(self.retry_delay)
    
    def get_file_metadata(self, file_path: str) -> Optional[Dict[str, Any]]:
        """
        獲取文件元數據,包含完整錯誤處理
        """
        if not self.safe_check_exists(file_path):
            return None
        
        try:
            path = Path(file_path)
            stat_info = path.stat()
            
            return {
                'size': stat_info.st_size,
                'modified_time': stat_info.st_mtime,
                'access_time': stat_info.st_atime,
                'creation_time': getattr(stat_info, 'st_birthtime', None),
                'is_file': path.is_file(),
                'is_dir': path.is_dir(),
                'is_symlink': path.is_symlink(),
            }
            
        except OSError as e:
            logger.error(f"獲取文件元數據失敗: {file_path} - {e}")
            return None

# 使用示例
file_checker = RobustFileChecker()

# 檢查文件是否存在
exists = file_checker.safe_check_exists("/etc/passwd")
print(f"/etc/passwd 存在: {exists}")

# 獲取文件元數據
metadata = file_checker.get_file_metadata("/etc/passwd")
if metadata:
    print("文件元數據:", metadata)

總結

文件存在性檢測是Python編程中的基礎操作,但真正掌握這一技能需要理解其背后的復雜性。本文從基礎方法到高級應用,全面探討了Python中文件存在性檢測的各個方面。

??關鍵要點總結:??

  • ??方法選擇??:根據場景選擇合適的檢測方法,簡單檢查用os.path.exists(),文件操作前用EAFP風格
  • ??競爭條件??:在多線程/多進程環(huán)境中,文件狀態(tài)可能發(fā)生變化,需要適當的重試機制
  • ??性能考量??:批量檢查時考慮并行處理,頻繁檢查相同文件時使用緩存
  • ??錯誤處理??:完整的錯誤處理和日志記錄是生產環(huán)境代碼的必要條件
  • ??安全考慮??:檢查文件時要注意權限問題,特別是處理用戶輸入時

??最佳實踐建議:??

  • 使用pathlib進行現代Python文件路徑操作
  • 重要文件操作采用EAFP風格并包含適當的重試機制
  • 為頻繁的文件檢查操作實現緩存機制
  • 始終包含完整的錯誤處理和日志記錄
  • 在處理用戶提供的文件路徑時進行安全驗證

通過掌握這些技術和最佳實踐,開發(fā)者可以編寫出更加健壯、可靠的文件處理代碼,避免常見的陷阱和問題。文件存在性檢測雖然看似簡單,但卻是構建可靠應用程序的重要基礎。

到此這篇關于Python實現檢測文件是否存在的方法完整指南的文章就介紹到這了,更多相關Python檢測文件是否存在內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python selenium 三種等待方式詳解(必會)

    Python selenium 三種等待方式詳解(必會)

    這篇文章主要介紹了Python selenium 三種等待方式詳解(必會)的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-09-09
  • Python3.5集合及其常見運算實例詳解

    Python3.5集合及其常見運算實例詳解

    這篇文章主要介紹了Python3.5集合及其常見運算,結合實例形式分析了Python3.5集合的定義、功能、交集、并集、差集等常見操作技巧與相關注意事項,需要的朋友可以參考下
    2019-05-05
  • 酷! 程序員用Python帶你玩轉沖頂大會

    酷! 程序員用Python帶你玩轉沖頂大會

    程序員用Python玩轉王思聰的《沖頂大會》,感興趣的小伙伴們可以參考一下
    2018-01-01
  • pytorch 預訓練模型讀取修改相關參數的填坑問題

    pytorch 預訓練模型讀取修改相關參數的填坑問題

    這篇文章主要介紹了pytorch 預訓練模型讀取修改相關參數的填坑問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Python實現音頻添加數字水印的示例詳解

    Python實現音頻添加數字水印的示例詳解

    數字水印技術可以將隱藏信息嵌入到音頻文件中而不明顯影響音頻質量,下面小編將介紹幾種在Python中實現音頻數字水印的方法,希望對大家有所幫助
    2025-04-04
  • Python中關于函數的具體用法范例以及介紹

    Python中關于函數的具體用法范例以及介紹

    函數是組織好的,可重復使用的,用來實現單一,或相關聯功能的代碼段。函數能提高應用的模塊性,和代碼的重復利用率。你已經知道Python提供了許多內建函數,比如print()。但你也可以自己創(chuàng)建函數,這被叫做用戶自定義函數
    2021-09-09
  • Python3 io文本及原始流I/O工具用法詳解

    Python3 io文本及原始流I/O工具用法詳解

    這篇文章主要介紹了Python3 io文本及原始流I/O工具用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-03-03
  • 基于Python開發(fā)簡單的圖片定位導出小程序

    基于Python開發(fā)簡單的圖片定位導出小程序

    在日常工作中,我們經常需要從大量圖片文件中篩選出包含特定名稱或編號的圖片,所以本文將使用Python開發(fā)一個圖片定位導出小程序,感興趣的小伙伴可以了解下
    2025-09-09
  • 4個的Python自動化腳本分享

    4個的Python自動化腳本分享

    這篇文章主要給大家分享了4個的Python自動化腳本,自動化腳本無需手動一次又一次地完成這些任務,非常方便,下面我能就一起進入文章來來了解實現吧,希望對你有所幫助
    2021-12-12
  • Python保姆式手把手帶你掌握異常的捕獲和處理

    Python保姆式手把手帶你掌握異常的捕獲和處理

    異常即非正常狀態(tài),在Python中使用異常對象來表示異常。若程序在編譯或運行過程中發(fā)生錯誤,程序的執(zhí)行過程就會發(fā)生改變,拋出異常對象,程序流進入異常處理。如果異常對象沒有被處理或捕捉,程序就會執(zhí)行回溯(Traceback)來終止程序
    2021-09-09

最新評論

怀来县| 汕头市| 家居| 芦溪县| 武乡县| 黄石市| 游戏| 萨迦县| 临清市| 双城市| 岳阳市| 南溪县| 贵州省| 泊头市| 马山县| 丰原市| 穆棱市| 德江县| 湄潭县| 碌曲县| 达日县| 扶风县| 东阿县| 新巴尔虎左旗| 普兰店市| 关岭| 牡丹江市| 株洲县| 股票| 宕昌县| 平山县| 海阳市| 望江县| 太白县| 海兴县| 尖扎县| 石首市| 屏东县| 财经| 新平| 嘉义县|