python应用实例
- 0.python基础
- [1. python获取文件夹下所有文件的两种方式](#1. python获取文件夹下所有文件的两种方式)
- [2. python 读写csv文件](#2. python 读写csv文件)
- [3. python 读写xml文件](#3. python 读写xml文件)
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']
###