如何使用Python自动化格式化文本,为每行国家代码添加引号和逗号
Python实现国家代码格式化处理
实现代码
# 读取存储国家代码的txt文件 with open("country_code.txt", "r", encoding="utf-8") as input_file: code_list = [line.strip() for line in input_file if line.strip()] # 格式化处理每一行代码 result_list = [f"'{code}'," for code in code_list] # 若需要最后一行末尾不带逗号,取消注释下面两行代码 # if result_list: # result_list[-1] = result_list[-1][:-1] # 输出到新文件 with open("formatted_code.txt", "w", encoding="utf-8") as output_file: output_file.write("\n".join(result_list))
说明
- 将代码中的
country_code.txt替换为你本地的原文件路径即可运行,处理后的内容会保存到同目录的formatted_code.txt文件中 - 代码自动过滤了原文件中的空行,生成结果和要求的格式完全匹配
内容的提问来源于stack exchange,提问作者Stefano Mauro
相关产品推荐
相关产品推荐

