CSVs in Python

本文介绍了两种将CSV文件转换为内存中数据结构的方法:一种是将每行数据存储为列表,另一种是将每行数据存储为字典。通过使用Python的unicodecsv库,文章详细展示了如何读取CSV文件并将数据存储为列表形式,以便进一步处理。

#Representing a CSV as  a   list   of  rows 

#Option 1: Each  row is  a  list 

csv=[['A1','A2','A3'],

          ['B1','B2','B3']]


#Option 2:Each row is a dictionary

csv=[{'name1':'A1','name2':'A2','name3','A3'},

           {'name1':'B1','name2':'B2','name3':'B3'}]


#to read in the student enrollments and print out the first record

########the first way

import unicodecsv

enrollments=[]       ##first,I creat a list of enrollments

f=open('enrollments.csv','rb')   ## Then,I open the file.The mode,rb,here,means that the file will be opened for reading,and the b flag changes the 

                                                    format of  how the file is read.The CSV documentation page mentions that I need to use this  when i use this  library

reader=unicodecsv.DictReader(f)  ###DictReader which means each row will be a dictionary,I chose this since our data does have  a header row,and

                                                    this will allow me to refer to each colum by its name,rather than its number.Now the reader won't  actually be a list of rows.

                                       instead it will be something called  interator.---is that the interator let's you writer a for  loop to access each element,but only once


for row in reader:

    enrollments.append(row)


f.close()

enrollments[0]

############the second way

import unicodecsv

with open('enrollments.csv','rb') as f:

    reader=unicodecsv.DictReader(f)

    enrollments=list(reader)

enrollments[0]

### 使用Python根据条件筛选文件 在Python中可以根据多种条件来筛选文件,这通常涉及到遍历目录中的文件并应用特定逻辑判断哪些文件应被选中。下面介绍几种常见的方式。 #### 基于文件名模式匹配筛选文件 当目标是从大量文件里挑选出名称符合一定规律的那些时,可以利用`os.listdir()`函数获取指定路径下的所有文件名列表,并通过字符串操作或正则表达式来进行过滤[^2]: ```python import re import os def select_files_by_pattern(directory, pattern): selected_files = [] for filename in os.listdir(directory): if re.match(pattern, filename): full_path = os.path.join(directory, filename) selected_files.append(full_path) return selected_files ``` 此方法适用于已知确切命名规则的情况;如果只是简单比较部分字符相同,则可以直接使用`str.startswith()`, `str.endswith()` 或者直接用等于号(`==`)做对比[^3]。 #### 根据Excel表格内的字段值筛选对应文件 有时需要依据外部数据源(比如Excel表)里的记录去定位相应的文件。此时可先读取Excel文档得到所需的信息列,再循环检查每个文件是否符合条件后再决定复制与否: ```python import pandas as pd import shutil df = pd.read_excel('./data.xlsx') for file_name in os.listdir(source_dir): fid_part = file_name.split('_')[index_of_fid_in_filename] if any(str(fid) == fid_part for fid in df['FID']): src_file = os.path.join(source_dir, file_name) dst_file = os.path.join(destination_dir, file_name) shutil.copy(src_file, dst_file) print("Selection completed.") ``` 这段代码展示了如何基于DataFrame对象内部的数据项与待处理文件之间的关联关系完成精准的选择工作。 #### 批量处理CSV文件内容作为筛选标准 对于存储结构化数据的CSV文件而言,可以通过Pandas库加载这些资源并对其中的内容执行查询语句从而达到目的[^4]: ```python import glob import pandas as pd all_csvs = glob.glob(path_to_folder + "*.csv") selected_dataframes = [] for csv_file in all_csvs: temp_df = pd.read_csv(csv_file) filtered_rows = temp_df[temp_df['column_name'].isin(target_values)] if not filtered_rows.empty: selected_dataframes.append(filtered_rows) final_result = pd.concat(selected_dataframes).reset_index(drop=True) ``` 这里实现了对多个CSV文件内特定列值属于给定集合的所有行进行提取的功能。 #### XML文件节点属性或文本内容为基础的筛选 针对XML类型的配置或其他形式描述性的文件,借助ElementTree模块解析其树状结构之后便能方便地访问各个标签及其子元素,进而实施更复杂的检索策略[^5]: ```python from xml.etree import ElementTree as ET tree = ET.parse(xml_file_path) root = tree.getroot() interesting_elements = root.findall(".//element[@attribute='value']") # Or search by text content within elements text_matches = [elem.text for elem in root.iter(tag="some_tag") if "target string" in (elem.text or '')] if interesting_elements or text_matches: # Do something with the found items... ``` 上述例子说明了怎样按照XML文档中定义好的标记特征选取感兴趣的片段。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值