这就是我要做的事情:
读取文本文件的内容,其中每行包含两个以逗号分隔的数字(如10, 5\n
,12, 8\n
,...)
将这两个数字相加
在新文本文件中写入两个原始数字,求和结果= 10 + 5 = 15\n
,12 + 8 = 20\n
,...
到目前为止,我已经有了这个:
import os
import sys
relative_path = "Homework 2.txt"
if not os.path.exists(relative_path):
print "not found"
sys.exit()
read_file = open(relative_path, "r")
lines = read_file.readlines()
read_file.close()
print lines
path_output = "data_result4.txt"
write_file = open(path_output, "w")
for line in lines:
line_array = line.split()
print line_array
答案 0 :(得分:0)
让你的上一个for
循环看起来像这样:
for line in lines:
splitline = line.strip().split(",")
summation = sum(map(int, splitline))
write_file.write(" + ".join(splitline) + " = " + str(summation) + "\n")
关于这种方式的一个好处是你可以在一条线上拥有任意数量的数字,它仍然可以正确显示。
答案 1 :(得分:0)
你需要对python有一个很好的理解才能理解这一点。
首先,阅读文件,通过换行(\n
)
对于每个表达式,计算答案并写出来。请记住,您需要将数字转换为整数,以便将它们加在一起。
with open('Original.txt') as f:
lines = f.read().split('\n')
with open('answers.txt', 'w+') as f:
for expression in lines: # expression should be in format '12, 8'
nums = [int(i) for i in expression.split(', ')]
f.write('{} + {} = {}\n'.format(nums[0], nums[1], nums[0] + nums[1]))
# That should write '12 + 8 = 20\n'
答案 2 :(得分:-1)
似乎输入文件是csv所以只需在python中使用csv reader模块。
输入文件作业2.txt
1, 2
1,3
1,5
10,6
脚本
import csv
f = open('Homework 2.txt', 'rb')
reader = csv.reader(f)
result = []
for line in list(reader):
nums = [int(i) for i in line]
result.append(["%(a)s + %(b)s = %(c)s" % {'a' : nums[0], 'b' : nums[1], 'c' : nums[0] + nums[1] }])
f = open('Homework 2 Output.txt', 'wb')
writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for line in result:
writer.writerow(line)
输出文件是Homework 2 Output.txt
1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
10 + 6 = 16