python数据分析中,想把一些变量保存到文件中,利用print方法和io类即可


import io
import sys

# 假设 sorted_docs 是你想要打印的变量
# sorted_docs = ['apple', 'banana', 'cherry']

# 创建 StringIO 对象
output = io.StringIO()

# 将标准输出重定向到 StringIO 对象
sys.stdout = output

# 执行 print 函数,输出将被写入 StringIO 对象
print(sorted_docs)

# 重定向标准输出回控制台
sys.stdout = sys.__stdout__

# 获取 StringIO 对象中的内容
printed_string = output.getvalue()

with open('sorted_docs_knrm.txt', 'w', encoding='utf-8') as file:
    file.write(printed_string)

# 打印保存的字符串
# print(printed_string)

# 关闭 StringIO 对象
output.close()

# 创建 StringIO 对象
output = io.StringIO()

# 将标准输出重定向到 StringIO 对象
sys.stdout = output

# 执行 print 函数,输出将被写入 StringIO 对象
print(all_scores)

# 重定向标准输出回控制台
sys.stdout = sys.__stdout__

# 获取 StringIO 对象中的内容
printed_string = output.getvalue()

with open('all_scores_knrm.txt', 'w', encoding='utf-8') as file:
    file.write(printed_string)

# 打印保存的字符串
# print(printed_string)

# 关闭 StringIO 对象
output.close()

# print(all_scores)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.