簡體   English   中英

Python:從.txt文件讀取行並使用它們進行計算

[英]Python: Reading lines from .txt file and calculating with them

希望您到目前為止過得愉快!

我正在嘗試讀取一個.txt文件,該文件中存儲了值並通過跳行將其彼此分開,然后使用這些值進行計算。

我試圖弄清楚如何使用Python腳本執行此操作。

假設這是我的文本文件的內容:

0.1 #line(0)
1.0
2.0
0.2 #line(3)
1.1
2.1
0.3 #line(6)
1.2
2.2
...

基本上,我將實現一個計算以下內容的操作:

第一步,將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     

有誰知道如何使它工作?

任何提示將不勝感激!

謝謝,史蒂夫

這將一次將三個數字相乘並將三個乘積寫入另一個文件:

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

在這里next(fobj_in)總是嘗試讀取下一行。 如果沒有更多行,則會引發StopIteration異常。 except StopIteration:捕獲此異常並終止循環。 列表[float(next(fobj_in)) for _ in range(3)]將從三行讀取的三個數字轉換為浮點數字。 現在,將thee數相乘就可以索引到列表numbers

你可以這樣做:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM