1

我无法弄清楚为什么我会收到 ValueError 'Invalid literal for int() with base 10: 'addin.txt'

out = open('addout.txt', 'w')

for line in open(int('addin.txt')):
    line = line.strip()
out.write((line [0] + line[1]) + (line [3] + line [4]))
out.close
4

1 回答 1

1

这是您的代码的更正版本,其中包含一些我希望您会发现有用的注释。

# open the file in as writable
out = open('addout.txt', 'w')

# go through each line of the input text
for line in open('addin.txt'):
    # split into parts (will return two strings if there are two parts)
    # this is syntax sugar for:
    #   parts = line.split()
    #   l = parts[0]
    #   r = parts[1]
    l,r = line.split()

    # parse each into a number and add them together
    sum = int(l) + int(r)

    # write out the result as a string, not forgetting the new line
    out.write(str(sum)+"\n")

# clean up your file handle
out.close()

核心位是int(somestring). 在这里阅读。如果您需要指定不同的基数,它看起来像int(somestring, base=8).

我希望这有帮助。

于 2013-03-20T06:53:39.707 回答