Python如何将每条不同邀请语句分别写入独立的TXT文件中
婚礼请柬独立文件生成代码修正方案
现有代码核心问题如下:
- 所有请柬内容都写入固定名称的
wedding_invite.txt,每次循环都会覆盖上一个宾客的内容,没有生成独立文件 event_details.txt的内容在print语句中已经被读取过一次,文件指针移动到末尾,后续write操作再次读取会返回空值str.join()用法错误,该方法只能接收单个可迭代对象作为参数,不能直接传入多个独立字符串- 循环内反复打开关闭
event_details.txt属于冗余操作,效率低下 - 写入内容未添加换行符,最终生成的文件内容会挤在同一行
修正后代码如下:
import os # 先一次性读取活动详情,无需循环内反复读取 if os.path.isfile("event_details.txt"): with open("event_details.txt", "r", encoding="utf-8") as e: event_content = e.read() else: event_content = "" print("警告:未找到event_details.txt文件,活动详情部分为空") if os.path.isfile("guest_list.txt"): with open("guest_list.txt", "r", encoding="utf-8") as infile: for line in infile: # 跳过空行 line = line.strip() if not line: continue split_line = line.split() # 处理姓名格式异常的行 if len(split_line) < 2: print(f"跳过格式错误的来宾行:{line}") continue first_name = split_line[0] last_name = split_line[1] # 用宾客姓名生成独立文件名,避免重复覆盖 file_name = f"wedding_invite_{first_name}_{last_name}.txt" # 组装完整请柬内容 invite_content = f"""Dear {first_name} {last_name} With great pleasure we are delighted to invite you to our wedding. We would be honored if you and your family could save the date. {event_content}""" # 写入对应独立文件 with open(file_name, "w", encoding="utf-8") as w: w.write(invite_content)
内容的提问来源于stack exchange,提问作者Flower
相关产品推荐
相关产品推荐

