3 回答

TA貢獻1998條經驗 獲得超6個贊
您可以創建一個生成器(它也會刪除 EOL 字符,如果您想要不同的東西,您可以刪除rstrip):
def readpairsoflines(f):
l1 = f.readline().rstrip('\n')
for l2 in f:
l2 = l2.rstrip('\n')
yield l1, l2
l1 = l2
并像這樣使用它:
with open(filename) as f:
for l1, l2 in readpairsoflines(f):
# Do something with your pair of lines, for example print them
print(f'{l1} and {l2}')
結果:
100 and 200
200 and 300
300 and 400
通過這種方法,僅讀取兩行并將其保存在內存中。因此,它也適用于可能需要考慮內存問題的大文件。

TA貢獻1802條經驗 獲得超10個贊
我總是喜歡簡單易讀的解決方案(盡管有時不太“Pythonic”)。
with open("example.txt") as f:
old = f.readline().rstrip()
for line in f:
line = line.rstrip()
print("{} and {}".format(old, line))
old = line
在循環其余行之前執行第一次讀取
然后,打印所需的輸出,并old更新字符串
需要調用 ion命令rstrip()來刪除不需要的尾隨'\n'
我認為如果文件少于兩行,則無需打印任何內容;可以輕松修改代碼以管理特殊情況下的任何需求
輸出:
100 and 200
200 and 300
300 and 400

TA貢獻1801條經驗 獲得超8個贊
現在我建議像這樣將文檔分成換行符
with open('params.txt') as file:
data = file.read()
data = data.split('\n')
for index, item in enumerate(data):
try:
print(str(item) + ' ' + str(data[index + 1]))
except IndexError:
print(str(item))
并使用一些列表邏輯打印您需要的內容,因此此代碼的作用是創建所需值的列表(對于非常大的文件效率不高)并獲取它們的索引,因此當它打印該項目時,它還會打印列表中的下一個項目,并且它對每個項目索引錯誤執行此操作是因為最后一項不會有下一項,但您也可以通過使用 if else 語句來解決它
添加回答
舉報