我无法弄清楚为什么我得到了ValueError'对于带有基数为10的int()的无效文字:'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
答案 0 :(得分: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)
。阅读here。如果您需要指定不同的基数,它看起来像int(somestring, base=8)
。
我希望这会有所帮助。