[英]Python: Reading lines from .txt file and calculating with them
I hope you are having pleasant holidays so far! 希望您到目前为止过得愉快!
I am trying to read a .txt file in which values are stored and separated from each other by a line skip and then calculate with the values. 我正在尝试读取一个.txt文件,该文件中存储了值并通过跳行将其彼此分开,然后使用这些值进行计算。
I am trying to figure out how to do this using a Python script. 我试图弄清楚如何使用Python脚本执行此操作。
Let's say this is the content of my text file: 假设这是我的文本文件的内容:
0.1 #line(0)
1.0
2.0
0.2 #line(3)
1.1
2.1
0.3 #line(6)
1.2
2.2
...
Basically I would to implement an operation that calculates: 基本上,我将实现一个计算以下内容的操作:
line(0)*line(1)*line(2) in the first step, writes it into another .txt file and then continues with line(3)*line(4)*line(5) and so on: 第一步,将line(0)* line(1)* line(2)写入另一个.txt文件,然后继续执行line(3)* line(4)* line(5) ,依此类推:
with open('/filename.txt') as file_:
for line in file_:
for i in range(0,999,1):
file = open('/anotherfile.txt')
file.write(str(line(i)*line(i+1)*line(i+2) + '\n')
i += 3
Does anyone have an idea how to get this working? 有谁知道如何使它工作?
Any tips would be appreciated! 任何提示将不胜感激!
Thanks, Steve 谢谢,史蒂夫
This would multiply three numbers at a time and write the product of the three into another file: 这将一次将三个数字相乘并将三个乘积写入另一个文件:
with open('numbers_in.txt') as fobj_in, open('numbers_out.txt', 'w') as fobj_out:
while True:
try:
numbers = [float(next(fobj_in)) for _ in range(3)]
product = numbers[0] * numbers[1] * numbers[2]
fobj_out.write('{}\n'.format(product))
except StopIteration:
break
Here next(fobj_in)
always tries to read the next line. 在这里
next(fobj_in)
总是尝试读取下一行。 If there is no more line a StopIteration
exception is raised. 如果没有更多行,则会引发
StopIteration
异常。 The except StopIteration:
catches this exception and terminates the loop. except StopIteration:
捕获此异常并终止循环。 The list comprehension [float(next(fobj_in)) for _ in range(3)]
converts three numbers read from three lines into floating point numbers. 列表
[float(next(fobj_in)) for _ in range(3)]
将从三行读取的三个数字转换为浮点数字。 Now, multiplying the thee numbers is matter of indexing into the list numbers
. 现在,将thee数相乘就可以索引到列表
numbers
。
You can do this: 你可以这样做:
file = open('/anotherfile.txt','w')
i=0
temp=1
with open('/filename.txt') as file_:
for line in file_:
temp = temp*int(line)
if(i>1 && i%3==0):
file.write(str(temp)+'\n')
temp=1
i += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.