You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 17:06:01