Python,将整数写入.txt'fi

2024-06-02 05:09:35 发布

您现在位置:Python中文网/ 问答频道 /正文

使用pickle函数是将整数写入文本文件的最快和最健壮的方法吗?

以下是我目前掌握的语法:

import pickle

pickle.dump(obj, file)

如果有更好的选择,请随时告诉我。

我的用例正在编写用户输入:

n=int(input("Enter a number: "))
  • 是的,人类需要阅读并编辑它
  • 档案里会有10个号码
  • Python可能需要稍后再阅读它。

Tags: 方法函数用户importobjinput语法整数
3条回答

我觉得这样做比较简单:

number = 1337

with open('filename.txt', 'w') as f:
  f.write('%d' % number)

但这实际上取决于您的用例。

result = 1

f = open('output1.txt','w')  # w : writing mode  /  r : reading mode  /  a  :  appending mode
f.write('{}'.format(result))
f.close()

阅读

f = open('output1.txt', 'r')
input1 = f.readline()
f.close()

print(input1)

使用python 2,您还可以执行以下操作:

number = 1337

with open('filename.txt', 'w') as f:
  print >>f, number

我个人在不需要格式化的时候使用这个。

相关问题 更多 >