Python第七周作业
文章目录
- Python第七周作业
1.使用
open
以只读模式打开文件data.txt
,并逐行打印内容
2.使用pathlib
模块获取当前脚本的绝对路径,并创建logs
目录(若不存在)
3.递归遍历目录data
,输出所有.csv
文件的路径
1.使用open
以只读模式打开文件data.txt
,并逐行打印内容;
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
目录(若不存在);
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
文件的路径;
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())