程序员开发实例大全宝库

网站首页 > 编程文章 正文

从Java到Python学习指南(下篇)

zazugpt 2025-03-12 22:15:06 编程文章 189 ℃ 0 评论

一、异常处理与文件操作

1. 异常处理对比

Java 异常处理

在 Java 中,异常处理是通过 try-catch-finally 语句块来实现的,同时还存在受检查异常(Checked Exception)和非受检查异常(Unchecked Exception)的区别。以下是一个简单的 Java 异常处理示例:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class JavaExceptionHandling {
    public static void main(String[] args) {
        try {
            File file = new File("nonexistent.txt");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + e.getMessage());
        } finally {
            System.out.println("无论是否发生异常,这里的代码都会执行。");
        }
    }
}

在上述代码中,try 块中包含可能会抛出异常的代码。如果 File 对象指定的文件不存在,Scanner 构造函数会抛出 FileNotFoundException 异常,该异常会被 catch 块捕获并处理。finally 块中的代码无论是否发生异常都会执行。

Python 异常处理

Python 的异常处理使用 try-except-finally 结构,相对更加简洁。示例如下:

try:
    with open('nonexistent.txt', 'r') as file:
        for line in file:
            print(line.strip())
except FileNotFoundError:
    print("文件未找到")
finally:
    print("无论是否发生异常,这里的代码都会执行。")

在 Python 中,try 块包含可能引发异常的代码。如果文件不存在,会抛出 FileNotFoundError 异常,被对应的 except 块捕获并处理。finally 块同样会在最后执行。Python 还支持 else 子句,当 try 块中没有发生异常时会执行 else 块中的代码。

2. 文件操作对比

Java 文件操作

Java 的文件操作相对复杂,需要处理多个类和异常。以下是一个简单的 Java 文件读取和写入示例:

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class JavaFileOperations {
    public static void main(String[] args) {
        // 写入文件
        try (FileWriter writer = new FileWriter("test.txt")) {
            writer.write("Hello, Java File!");
        } catch (IOException e) {
            System.out.println("写入文件时发生错误: " + e.getMessage());
        }

        // 读取文件
        try {
            List lines = Files.readAllLines(Paths.get("test.txt"));
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }
    }
}

在 Java 中,写入文件可以使用 FileWriter 类,读取文件可以使用 Files 类的静态方法。同时,需要处理 IOException 异常。

Python 文件操作

Python 的文件操作更加简洁和直观。示例如下:

# 写入文件
with open('test.txt', 'w') as file:
    file.write('Hello, Python File!')

# 读取文件
with open('test.txt', 'r') as file:
    content = file.read()
    print(content)

在 Python 中,使用 open 函数打开文件,通过不同的模式(如 'w' 表示写入,'r' 表示读取)进行文件操作。with 语句会自动管理文件的关闭,避免了手动调用 close 方法。

二、实战项目演练 - 简单数据分析

1. 项目背景

我们要对一个包含学生成绩的 CSV 文件进行简单的数据分析,计算平均分、最高分和最低分。

2. Java 实现

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class JavaDataAnalysis {
    public static void main(String[] args) {
        List scores = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader("scores.csv"))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] values = line.split(",");
                for (String value : values) {
                    try {
                        scores.add(Integer.parseInt(value));
                    } catch (NumberFormatException e) {
                        System.out.println("数据格式错误: " + e.getMessage());
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }

        if (!scores.isEmpty()) {
            int sum = 0;
            for (int score : scores) {
                sum += score;
            }
            double average = (double) sum / scores.size();
            int max = Collections.max(scores);
            int min = Collections.min(scores);

            System.out.println("平均分: " + average);
            System.out.println("最高分: " + max);
            System.out.println("最低分: " + min);
        }
    }
}

在 Java 中,需要使用 BufferedReader 读取 CSV 文件,将每行数据按逗号分割并转换为整数存储在 List 中。然后计算平均分、最高分和最低分。

3. Python 实现

import csv

scores = []
try:
    with open('scores.csv', 'r', newline='') as csvfile:
        reader = csv.reader(csvfile)
        for row in reader:
            for value in row:
                try:
                    scores.append(int(value))
                except ValueError:
                    print(f"数据格式错误: {value}")
except FileNotFoundError:
    print("文件未找到")

if scores:
    average = sum(scores) / len(scores)
    max_score = max(scores)
    min_score = min(scores)

    print(f"平均分: {average}")
    print(f"最高分: {max_score}")
    print(f"最低分: {min_score}")

在 Python 中,使用 csv 模块读取 CSV 文件更加方便。将数据存储在列表中后,使用内置函数 sum、max 和 min 轻松计算平均分、最高分和最低分。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表