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())
相关推荐
ChinaRainbowSea3 分钟前
7. LangChain4j + 记忆缓存详细说明
java·数据库·redis·后端·缓存·langchain·ai编程
stormsha3 分钟前
飞算JavaAI炫技赛电商系统商品管理模块的架构设计与实现
java·架构·鸿蒙系统
minh_coo4 分钟前
Spring框架事件驱动架构核心注解之@EventListener
java·后端·spring·架构·intellij-idea
空山新雨(大队长)7 分钟前
HTML第八课:HTML4和HTML5的区别
前端·html·html5
翻滚丷大头鱼12 分钟前
Java 集合Collection—List
java·开发语言
爬虫程序猿30 分钟前
《京东商品详情爬取实战指南》
爬虫·python
胡耀超32 分钟前
4、Python面向对象编程与模块化设计
开发语言·python·ai·大模型·conda·anaconda
猫头虎-前端技术42 分钟前
浏览器兼容性问题全解:CSS 前缀、Grid/Flex 布局兼容方案与跨浏览器调试技巧
前端·css·node.js·bootstrap·ecmascript·css3·媒体
阿珊和她的猫42 分钟前
探索 CSS 过渡:打造流畅网页交互体验
前端·css