Python,将整数写入“.txt”文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16131233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python, writing an integer to a '.txt' file
提问by clickonMe
Would using the pickle function be the fastest and most robust way to write an integer to a text file?
使用 pickle 函数是将整数写入文本文件的最快、最健壮的方法吗?
Here is the syntax I have so far:
这是我到目前为止的语法:
import pickle
pickle.dump(obj, file)
If there is a more robust alternative, please feel free to tell me.
如果有更强大的替代方案,请随时告诉我。
My use case is writing an user input:
我的用例正在编写用户输入:
n=int(input("Enter a number: "))
- Yes, A human will need to read it and maybe edit it
- There will be 10 numbers in the file
- Python may need to read it back later.
- 是的,人类需要阅读它并可能对其进行编辑
- 文件中有 10 个数字
- Python 可能需要稍后再读一遍。
采纳答案by Alex
I think it's simpler doing:
我认为这样做更简单:
number = 1337
with open('filename.txt', 'w') as f:
f.write('%d' % number)
But it really depends on your use case.
但这实际上取决于您的用例。
回答by HennyH
The following opens a while and appends the following number to it.
下面打开一段时间并在其后面附加以下数字。
def writeNums(*args):
with open('f.txt','a') as f:
f.write('\n'.join([str(n) for n in args])+'\n')
writeNums(input("Enter a numer:"))
回答by Benares
With python 2, you can also do:
使用 python 2,您还可以执行以下操作:
number = 1337
with open('filename.txt', 'w') as f:
print >>f, number
I personally use this when I don't need formatting.
当我不需要格式化时,我个人会使用它。
回答by Dane Lee
Write
写
result = 1
f = open('output1.txt','w') # w : writing mode / r : reading mode / a : appending mode
f.write('{}'.format(result))
f.close()
Read
读
f = open('output1.txt', 'r')
input1 = f.readline()
f.close()
print(input1)
回答by Adam
I just encountered a similar problem. I used a simple approach, saving the integer in a variable, and writing the variable to the file as a string. If you need to add more variables you can always use "a+" instead of "w" to append instead of write.
我刚刚遇到了类似的问题。我使用了一种简单的方法,将整数保存在一个变量中,然后将该变量作为字符串写入文件。如果您需要添加更多变量,您始终可以使用“a+”而不是“w”来追加而不是写入。
f = open("sample.txt", "w")
integer = 10
f.write(str(integer))
f.close()
Later you can use float to read the file and you wont throw and error.
稍后您可以使用 float 读取文件,并且不会抛出错误。

