1.Read and write text files
1.1name_sorter
# 定义从文件读取姓名列表的函数
def get_names_from_file(file_name):
with open(file_name, 'r') as file: # 补充代码实现以读模式打开文件
names = [] # 初始姓名列表为空
for line in file:
name = line.rstrip()
names.append(name)
return names # 返回姓名列表
# 定义姓名列表排序函数
def sort_names(names):
return sorted(names, reverse=True) # 补充代码对输入的姓名列表从大到小排序
# 如果是按照字母顺序排序,则可以使用 sorted(names)
# 定义向文件中写姓名信息的函数
def write_names_info_to_file(file_name, names):
with open(file_name, 'w') as f: # 补充代码实现以写模式打开文件
first_line = f"Total of {len(names)} names\n"
f.write(first_line)
sep_line = '-' * len(first_line) + '\n'
f.write(sep_line)
# 补充代码实现循环姓名列表写入文件,注意每个名字后要有回车符
for name in names:
f.write(name + '\n')
def main():
# 调用函数读取 names.txt 文件中姓名列表
names = get_names_from_file("src/step1_name_sorter/names.txt")
# 调用函数对姓名列表排序
sorted_names = sort_names(names)
# 调用函数将排序后的姓名列表信息写入 new_names.txt 文件
write_names_info_to_file("src/step1_name_sorter/new_names.txt", sorted_names)
if __name__ == "__main__":
main()
1.2parsing_data_file
def get_record_info_from_file(filename):
records_list = [] # 初始化记录列表
keys = ['last', 'first', 'salary'] # 表格头数据信息
max_len_str = max(len(key) for key in keys) # 计算表格头最长字符串
with open(filename, 'r') as file: # 以读模式打开文件
for l in file.readlines(): # 循环文件每一行
record = [field.strip() for field in l.split(',')] # 获取逗号分割的字符串数据,并删除右侧空格和回车
records_list.append(record) # 将本行记录信息添加到记录列表中
max_len_str = max(max_len_str, max(len(field) for field in record)) # 更新计算所有记录信息中最长字符串
return records_list, max_len_str # 返回记录列表和最长字符串的长度
def print_headings(column_len):
headings = ['Last', 'First', 'Salary'] # 表头每列信息列表
for heading in headings: # 循环每列的头信息
new_heading = heading.ljust(column_len) # 右补齐空格到给定列长度
print(new_heading, end='') # 打印该列补齐后的表头信息
print() # 打印换行
print('-' * (column_len * len(headings))) # 打印与表头总长等长的连字符行
def print_records(records_list, column_len):
for record in records_list: # 循环记录列表
for value in record: # 循环一行记录中的多个信息值
new_value = value.ljust(column_len) # 右补齐空格到给定列长度
print(new_value, end='') # 打印补齐后的值信息
print() # 打印换行
if __name__ == "__main__":
# 调用读取记录和统计打印信息中最大字符串长度的函数
records_list, max_str_len = get_record_info_from_file("src/step2_parsing_data_file/names.csv")
# 调用打印表头函数
print_headings(max_str_len + 1)
# 调用打印记录信息函数
print_records(records_list, max_str_len + 1)
1.3product_search
# 定义读取文件中的产品信息,返回字典数据的函数,可借助 eval() 函数
def get_products_from_file(filename):
with open(filename) as file: # 以读模式打开文件
data = eval(file.read())
return data
# 定义从所有产品列表中查找给定名称产品的函数
def get_product_from_products(product_name, products):
found = [p for p in products if p['name'] == product_name]
if len(found) > 0:
return found[0]
# 定义打印给定产品信息函数
def print_product(product):
print(f"name: {product['name']}")
print(f"price: {product['price']}")
print(f"quantity: {product['quantity']}")
# 主流程:依据用户输入名称查找库存产品并打印信息,直到在库存中能找到用户指定产品
if __name__ == "__main__":
products = get_products_from_file("src/step3_product_search/products.json")
while True:
product_name = input('What is the product name? ')
# 调用函数在库存中寻找指定名产品
product = get_product_from_products(product_name, products['products'])
if product: # 在库存中找到产品
print_product(product) # 调用函数打印产品信息
break
else:
print('Sorry, that prouct was not found in our inventory.')
2.Read and write excel files
2.1to_excel
import openpyxl
# 创建一个新的工作簿
wb = openpyxl.Workbook()
ws = wb.active
# 准备要写入的数据
title_data = ['Name', 'Age', 'City'] # 标题行数据
datas = [['Alice', 25, 'New York'], ['Bob', 30, 'Los Angeles'], ['Charlie', 35, 'Chicago']]
# 添加标题行
ws.append(title_data)
# 遍历添加每行数据到工作表
for data in datas:
ws.append(data)
# 保存工作簿
wb.save('src/step1_to_excel/step1_output.xlsx')
print("数据已写入 src/step1_to_excel/step1_output.xlsx 文件")
2.2read_excel
import openpyxl
# 从 Excel 文件读取数据
wb = openpyxl.load_workbook('src/step2_read_excel/step2.xlsx')
ws = wb.active
# 按行打印读取的数据,工作表中一行数据在一行用空格间隔显示并在数据每行最后加个空格
for row in ws.iter_rows(values_only=True):
print(*row, end=' ')
print()
# 读取特定单元格的内容
name = ws['A2'].value
age = ws['B2'].value
print("Name: %s, Age: %s" % (name, age))
2.3update_excel
import openpyxl
# 加载已有的 Excel 文件
wb = openpyxl.load_workbook('src/step3_update_excel/step3.xlsx')
ws = wb.active
# 修改数据:更新 Alice 的年龄为 26
for row in ws.iter_rows(min_row=2):
name = row[0].value
if name == 'Alice':
row[1].value = 26
# 删除 Bob 的行
for row in ws.iter_rows(min_row=2):
name = row[0].value
if name == 'Bob':
ws.delete_rows(row[0].row)
# 保存修改后的工作簿
wb.save('src/step3_update_excel/step3_output.xlsx')
print("已删除 Bob 的数据并保存到 src/step3_update_excel/step3_output.xlsx 文件")