python5

python应用实例

0.python基础

python基础1
python基础2
python基础3
python基础4

1. python获取文件夹下所有文件的两种方式

方法一:递归

python 复制代码
import os

def list_dir(text_list,dir_path):
    dir_files = os.listdir(dir_path)  # 得到该文件夹下所有的文件
    for file in dir_files:
        file_path = os.path.join(dir_path, file)  # 路径拼接成绝对路径
        if os.path.isfile(file_path):  # 如果是文件,就打印这个文件路径
            if file_path.endswith(".txt"):
                text_list.append(file_path)
        if os.path.isdir(file_path):  # 如果目录,就递归子目录
            list_dir(text_list,file_path)
    return text_list


if __name__ == '__main__':
    all_txt = []
    thesaurus_path = r"dir_path"
    text_list = list_dir(all_txt,thesaurus_path)
    for text in text_list:
        print(text)

方法二:os.walk()(推荐)

python 复制代码
import os

#遍历所有文件夹下的文件
def walk_files(path,endpoint=None):
    file_list = []
    for root,dirs,files in os.walk(path):
        for file in files:
            file_path = os.path.join(root,file)
            if file_path.endswith(endpoint):
                file_list.append(file_path)

    return file_list

if __name__ == '__main__':
    wav_path = r"dir_path"
    text_list = walk_files(wav_path, endpoint=".txt")
    print(text_list)

2. python 读写csv文件

写入

python 复制代码
# 导入CSV模块
import csv
 
# 1. 创建文件对象(指定文件名,模式,编码方式)
with open("file.csv", "w", encoding="gbk", newline="") as f:
    # 2. 基于文件对象构建 csv写入对象
    csv_writer = csv.writer(f)
    # 3. 构建列表头
    csv_writer.writerow(["name", "age", "gender"])
    # 4. 写入csv文件内容
    csv_writer.writerow(["jack", "18", "men"])
    csv_writer.writerow(["alex", "20", "women"])
    print("写入数据成功")
    # 5. 关闭文件
    f.close()

读取

方法1:csv.reader()

cpp 复制代码
import csv
with open('../data/test.csv') as csvfile:
    # 生成csv迭代器
    reader = csv.reader(csvfile)
    # 获取headers
    header = next(reader)
    print(header)
    # 遍历每一行
    for row in reader:
        print(row)
###        
['name', 'time']
['GF2_PMS1_E108.6_N18.7_20230129_L1A0007080026-MSS1.xml', '2023-01-29T10:37:22']
['GF2_PMS1_E108.6_N18.7_20230129_L1A0007080026-PAN1.xml', '2023-01-29T10:37:23']
['GF2_PMS1_E108.6_N18.9_20230129_L1A0007080016-MSS1.xml', '2023-01-29T10:37:20']
['GF2_PMS1_E108.6_N18.9_20230129_L1A0007080016-PAN1.xml', '2023-01-29T10:37:20']  
###      

3. python 读写xml文件

相关推荐
z落落22 分钟前
C#WinForm 窗体切换与窗体传值(登录跳转案例)+WinForm 窗体传值(从上往下传、从下往上传)
开发语言·windows·c#
CTA量化套保30 分钟前
期货量化程序 time.sleep 卡死:天勤单线程与 deadline 替代
python·区块链
allway235 分钟前
How to Echo Multiline to a File in Bash [3 Methods]
开发语言·chrome·bash
weixin_4624462336 分钟前
手把手教你用 Bash 脚本自动更新 /etc/hosts —— 自动绑定网卡 IP 与节点名
开发语言·tcp/ip·bash
一个梦醒了38 分钟前
安装git bash选项推荐
开发语言·git·bash
GIS数据转换器1 小时前
城市排水生命线安全运行监测平台深度解析
java·运维·人工智能·python·安全·数据挖掘·无人机
ct9781 小时前
React 状态管理方案深度对比
开发语言·前端·react
贤哥哥yyds1 小时前
GBK转UTF\-8编码自动转换工具 使用文档
python
数量技术宅1 小时前
2026量化前沿:从Reddit热帖到Python实战,如何用赫斯特指数(Hurst)狙击虚假突破?
开发语言·python
华如锦1 小时前
面了很多 Java转AI Agent方向,一些面试题总结
java·开发语言·人工智能·python·ai