Python,将整数写入'.txt'文件

cli*_*nMe 8 python performance pickle robustness

使用pickle函数是将整数写入文本文件的最快且最强大的方法吗?

这是我到目前为止的语法:

import pickle

pickle.dump(obj, file)
Run Code Online (Sandbox Code Playgroud)

如果有更强大的替代方案,请随时告诉我.

我的用例是写一个用户输入:

n=int(input("Enter a number: "))
Run Code Online (Sandbox Code Playgroud)
  • 是的,人类将需要阅读它并可能编辑它
  • 文件中将有10个数字
  • Python可能需要稍后再读.

Ale*_*lex 8

我认为做起来更简单:

number = 1337

with open('filename.txt', 'w') as f:
  f.write('%d' % number)
Run Code Online (Sandbox Code Playgroud)

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


Dan*_*Lee 5

result = 1

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

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

print(input1)
Run Code Online (Sandbox Code Playgroud)