在Python中处理文本文件并根据特定条件组合多行数据是一个常见的任务。以下是一个详细的解答,包括基础概念、优势、类型、应用场景以及示例代码。
if
语句)来检查特定条件是否满足。假设我们有一个文本文件data.txt
,内容如下:
ID: 1
Name: Alice
Age: 25
ID: 2
Name: Bob
Age: 30
ID: 3
Name: Charlie
Age: 35
我们希望将每个ID的相关信息组合成一行,格式为ID: Name, Age
。
def combine_lines(file_path):
combined_data = []
current_entry = {}
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
if line.startswith('ID:'):
if current_entry:
combined_data.append(f"{current_entry['ID']}: {current_entry['Name']}, {current_entry['Age']}")
current_entry = {}
current_entry['ID'] = line.split(': ')[1]
elif line.startswith('Name:'):
current_entry['Name'] = line.split(': ')[1]
elif line.startswith('Age:'):
current_entry['Age'] = line.split(': ')[1]
# Add the last entry if it exists
if current_entry:
combined_data.append(f"{current_entry['ID']}: {current_entry['Name']}, {current_entry['Age']}")
return combined_data
# 使用示例
file_path = 'data.txt'
result = combine_lines(file_path)
for line in result:
print(line)
open
函数以只读模式打开文件。ID:
、Name:
、Age:
)将数据存储到字典current_entry
中。ID:
行时,将之前的条目组合成所需格式并添加到结果列表combined_data
中。try-except
块捕获FileNotFoundError
并处理。通过这种方式,你可以灵活地根据条件组合多行文本数据,适用于各种实际应用场景。
领取专属 10元无门槛券
手把手带您无忧上云