如何在python

时间:2017-04-12 20:34:50

标签: python text

我需要创建一个程序,在python中添加和减去文本文件中的值,我在整个互联网上查找,但我找不到任何有用的东西。 这是我到目前为止所拥有的

f = int(input("Enter numbers to add products"))
x = open("testfile.txt","r+")
print(x + f)

x变量包含一个文本文件,其中包含数字7,当用户输入数字时,它应该添加用户对文本文件中的值所赋予的任何内容并打印该值。问题是我无法将它们加在一起并打印出总价值,任何帮助都会很棒。

3 个答案:

答案 0 :(得分:0)

您需要阅读文件内容,希望它包含看起来像整数的内容:

3

否则,您要求Python添加整数和文件。

testfile.txtwith open(...的内容是什么?

注意: someVectorDrawable = VectorDrawableCompat.create(context.getResources(), R.drawable.[some res id], null); 确保文件在读取后正确关闭,即使它不包含任何有效整数。

答案 1 :(得分:0)

在您的代码中,您尝试使用文件句柄添加整数,这没有任何意义。

这是一个工作代码,用于读取文件并执行所需的操作:

f = int(input("Enter numbers to add products"))
with open("testfile.txt","r") as fhandle:
    print(f + int(fhandle.read()))

读取文本文件,将内容转换为整数并打印添加到输入的结果。请注意,它非常脆弱:

  • 文件为空=>例外,
  • 文件包含除整数之外的其他内容=>例外...

答案 2 :(得分:0)

啊是的,这也有效

while (!MemoryProfiler.IsActive)
  Thread.Sleep(500);

// do something here #1
MemoryProfiler.Dump();

// do something here #2.1
if (MemoryProfiler.CanControlAllocations)
  MemoryProfiler.EnableAllocations();
// do something here #2.2, here will be collected allocations, but only in start mode
if (MemoryProfiler.CanControlAllocations)
  MemoryProfiler.DisableAllocations();
// do something here #2.3
MemoryProfiler.Dump();

// do something here #3
MemoryProfiler.Dump();

if (MemoryProfiler.CanDetach)
  MemoryProfiler.Detach();

我猜我只是犯了处理整数的错误