Python第七周作业

Python第七周作业

文章目录

1.使用open以只读模式打开文件data.txt,并逐行打印内容

2.使用pathlib模块获取当前脚本的绝对路径,并创建logs目录(若不存在)

3.递归遍历目录data,输出所有.csv文件的路径

1.使用open以只读模式打开文件data.txt,并逐行打印内容;

python 复制代码
import os
data_file = '/Users/hooper/Downloads/Study/马哥大模型1期-2025/作业/Python-第07周/data/data.txt'
def read_file(file_path):
    if os.path.exists(file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                print(line, end='')
read_file(data_file)

2.使用pathlib模块获取当前脚本的绝对路径,并创建logs目录(若不存在);

python 复制代码
from pathlib import Path
import os
# 获取当前脚本的绝对路径
current_path = Path(__file__).resolve().parent
# print(f"current_path: {current_path}")
# 方法一:
# 获取创建目录的路径并创建
logs_path = current_path/'logs'
logs_path.mkdir(exist_ok=True)
print(f"logs_path: {logs_path}")

# 方法二:
# 拼接创建目录的路径并创建
logs_path = os.path.join(current_path, 'logs')
if not os.path.exists(logs_path):
    os.makedirs(logs_path)
    print(f"{logs_path} creation complete.")
else:
    print(f"{logs_path} already exists.")

3.递归遍历目录data,输出所有.csv文件的路径;

python 复制代码
import os
from pathlib import Path
# 方法一:
find_path = '/Users/hooper/Downloads/Study/马哥大模型1期-2025/作业/Python-第07周/data'
if not os.path.exists(find_path):
    print(f"{find_path} is not exists")
else:
    for dirpath, dirnames, filenames in os.walk(find_path):
        for filename in filenames:
            if filename.endswith('.csv'):
                full_path = os.path.join(dirpath, filename)
                print(full_path)

# 方法二:
current_path = Path(__file__).resolve().parent
find_path = current_path/'data'
if not find_path.exists():
    print(f"{find_path} is not exists")
else:
    for csv_file in find_path.rglob('*.csv'):
        print(csv_file.resolve())
相关推荐
原则猫1 小时前
前端基础大厦
前端
陈随易3 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart3 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒5 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰6 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
竹林8186 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
用户8356290780517 小时前
Python 实现 PDF 文件加密与解密方法
后端·python
用户8356290780517 小时前
使用 Python 冻结与拆分 Excel 窗格教程
后端·python
karry_k7 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
妙码生花7 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go