我有一个像这样的文本文件(text.txt):
50 10 15 20 25
40 30 35 40 45
30 50 55 60 65
我已编辑此文件如下:
lines = [line.rstrip('\n') for line in open('text.txt')]
output = open('a.txt', 'w')
for line in lines:
line = line.split()
output.write('Values({},{},{},{},{});\n'.format(line[0], line[1],
line[2], line[3], line[4]))
output.close()
这是新的文本文件:
Values(50,10,15,20,25);
Values(40,30,35,40,45);
Values(30,50,55,60,65);
现在我想通过对其组件进行数学运算来编辑文件(原始 text.txt):
我想从第一个中的所有分量中减去 10 栏目
我想从其余部分的所有分量中减去 1 栏目
更具体地说,我正在看这个:
Values(40,9,14,19,24);
Values(30,29,34,39,44);
Values(20,49,54,59,64);
如何在此文本文件中实现这个简单的数学运算以获得上述结果作为输出? 谢谢!
最佳答案
试试这个:
lines = [line.rstrip('\n') for line in open('text.txt')]
output = open('a.txt', 'w')
for line in lines:
line = line.split()
# subtract 10 from all of the components in the first column
line[0] = int(line[0]) - 10
# subtract 1 from all of the components in the rest of the columns
line[1:] = [int(n) - 1 for n in line[1:]]
output.write('Values({},{},{},{},{});\n'.format(*line))
output.close()
关于python - 通过在文件内进行数学运算来编辑文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51355425/