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())
相关推荐
杨杨杨大侠6 小时前
都能接模型、RAG 和 MCP,Java Agent 框架到底差在哪?
java
破茧蝴蝶6 小时前
Python分布式爬虫完整教程
开发语言·python
Autumn_ing6 小时前
Design.md生成UI怎么验收?举例运营后台的颜色、状态和数据核对
前端·ui·ai·设计系统·paico·ai生成ui·design.md
benchmark_cc6 小时前
量化系统架构设计:为什么应该将数据获取与策略逻辑解耦?
python·数据分析·pandas·量化交易·股票数据·quantdash
凤山老林6 小时前
Spring Boot 启动冲刺:耗时剖析、懒加载策略与事件驱动初始化优化
spring boot·后端·python
小白快快跑哦7 小时前
python-字符串全解(六):正则表达式-逻辑运算或
python·正则表达式·字符串·逻辑运算
keyipatience7 小时前
JavaScript学习(1)书写位置,变量、数据类型、运算符
开发语言·前端·javascript·css·学习
Thinker QAQ7 小时前
并发编程(九):BlockingQueue 与 Channel——语言层的原子性、可见性与有序性
java·python·go·并发编程·channel·blockingqueue·message passing
道满科技7 小时前
Function Calling 参数总出错?只修参数就行
linux·windows·python
朱涛的自习室7 小时前
我给 Gemini 4 和 DeepSeek 搞了套「末位淘汰」,AI 干活会更猛吗?(Day 3)
android·前端·后端