python 文件读取
csv 读取
# import required libraries
import csv
import pandas as pd
from pprint import pprint
def print_basic_csv(file_name, delimiter=','):
"""This function extracts and prints csv content from given filename
Details: https://docs.python.org/2/library/csv.html
Args:
file_name (str): file path to be read
delimiter (str): delimiter used in csv. Default is comma (',')
Returns:
None
"""
csv_rows = list()
csv_attr_dict = dict()
csv_reader = None
# read csv
csv_reader = csv.reader(open(file_name, 'r'), delimiter=delimiter)
# iterate and extract data
for row in csv_reader:
print(row)
csv_rows.append(row)
# prepare attribute lists
for col in csv_rows[0]:
csv_attr_dict[col]=list()
# iterate and add data to attribute lists
for row in csv_rows[1:]:
csv_attr_dict['sno'].append(row[0])
csv_attr_dict['fruit'].append(row[1])
csv_attr_dict['color'].append(row[2])
csv_attr_dict['price'].append(row[3])
# print the result
print("\n\n")
print("CSV Attributes::")
pprint(csv_attr_dict)
def print_tabular_data(file_name,delimiter=","):
"""This function extracts and prints tabular csv content from given filename
Details: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
Args:
file_name (str): file path to be read
delimiter (str): delimiter used in csv. Default is comma ('\t')
Returns:
None
"""
df = pd.read_csv(file_name,sep=delimiter)
print(df)
'''
# example
print_basic_csv(r'tabular_csv.csv')
print_tabular_data(r'tabular_csv.csv')
'''
json
# import required libraries
import json
import pandas as pd
def print_nested_dicts(nested_dict,indent_level=0):
"""This function prints a nested dict object
Args:
nested_dict (dict): the dictionary to be printed
indent_level (int): the indentation level for nesting
Returns:
None
"""
for key, val in nested_dict.items():
if isinstance(val, dict):
print("{0} : ".format(key))
print_nested_dicts(val,indent_level=indent_level+1)
elif isinstance(val,list):
print("{0} : ".format(key))
for rec in val:
print_nested_dicts(rec,indent_level=indent_level+1)
else:
print("{0}{1} : {2}".format("\t"*indent_level,key, val))
def extract_json(file_name,do_print=True):
"""This function extracts and prints json content from a given file
Args:
file_name (str): file path to be read
do_print (bool): boolean flag to print file contents or not
Returns:
None
"""
try:
json_filedata = open(file_name).read()
json_data = json.loads(json_filedata)
if do_print:
print_nested_dicts(json_data)
except IOError:
raise IOError("File path incorrect/ File not found")
except ValueError:
ValueError("JSON file has errors")
except Exception:
raise
def extract_pandas_json(file_name,orientation="records",do_print=True):
"""This function extracts and prints json content from a file using pandas
This is useful when json data represents tabular, series information
Args:
file_name (str): file path to be read
orientation (str): orientation of json file. Defaults to records
do_print (bool): boolean flag to print file contents or not
Returns:
None
"""
try:
df = pd.read_json(file_name,orient=orientation)
if do_print:
print(df)
except IOError:
raise IOError("File path incorrect/ File not found")
except ValueError:
ValueError("JSON file has errors")
except Exception:
raise
'''
#example
extract_json(r'sample_json.json')
extract_pandas_json(r'pandas_json.json')
'''
xml
# import required libraries
import json
import pandas as pd
def print_nested_dicts(nested_dict,indent_level=0):
"""This function prints a nested dict object
Args:
nested_dict (dict): the dictionary to be printed
indent_level (int): the indentation level for nesting
Returns:
None
"""
for key, val in nested_dict.items():
if isinstance(val, dict):
print("{0} : ".format(key))
print_nested_dicts(val,indent_level=indent_level+1)
elif isinstance(val,list):
print("{0} : ".format(key))
for rec in val:
print_nested_dicts(rec,indent_level=indent_level+1)
else:
print("{0}{1} : {2}".format("\t"*indent_level,key, val))
def extract_json(file_name,do_print=True):
"""This function extracts and prints json content from a given file
Args:
file_name (str): file path to be read
do_print (bool): boolean flag to print file contents or not
Returns:
None
"""
try:
json_filedata = open(file_name).read()
json_data = json.loads(json_filedata)
if do_print:
print_nested_dicts(json_data)
except IOError:
raise IOError("File path incorrect/ File not found")
except ValueError:
ValueError("JSON file has errors")
except Exception:
raise
def extract_pandas_json(file_name,orientation="records",do_print=True):
"""This function extracts and prints json content from a file using pandas
This is useful when json data represents tabular, series information
Args:
file_name (str): file path to be read
orientation (str): orientation of json file. Defaults to records
do_print (bool): boolean flag to print file contents or not
Returns:
None
"""
try:
df = pd.read_json(file_name,orient=orientation)
if do_print:
print(df)
except IOError:
raise IOError("File path incorrect/ File not found")
except ValueError:
ValueError("JSON file has errors")
except Exception:
raise
'''
#example
extract_json(r'sample_json.json')
extract_pandas_json(r'pandas_json.json')
'''
不要高估三年后的自己,更不要低估十年后的自己。
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 复杂业务系统线上问题排查过程
· 通过抓包,深入揭秘MCP协议底层通信
· 记一次.NET MAUI项目中绑定Android库实现硬件控制的开发经历
· 糊涂啊!这个需求居然没想到用时间轮来解决
· 浅谈为什么我讨厌分布式事务
· 为大模型 MCP Code Interpreter 而生:C# Runner 开源发布
· 还在手写JSON调教大模型?.NET 9有新玩法
· 面试时该如何做好自我介绍呢?附带介绍样板示例!!!
· JavaScript 编年史:探索前端界巨变的幕后推手
· 独立开发:高效集成大模型,看这篇就够了