[英]python - extract a part of each line from text file
我有一個test.txt文件,其中包含:
yellow.blue.purple.green
red.blue.red.purple
而且我想在output.txt上只有每一行的第二和第三部分,就像這樣:
blue.purple
blue.red
這是python代碼:
with open ('test.txt', 'r') as file1, open('output.txt', 'w') as file2:
for line in file1:
file2.write(line.partition('.')[2]+ '\n')
但結果是:
blue.purple.green
blue.red.purple
如何僅占用每行的第二部分和第三部分?
謝謝
你可能想要
with open('test.txt', 'r') as file1, open('output.txt', 'w') as file2:
for line in file1:
file2.write(".".join(line.split('.')[1:3])+ '\n')
當您將split('.')
應用於例如yellow.blue.purple.green
,您將獲得值列表
["yellow", "blue", "purple", "green"]
通過切片[1:3]
,您可以獲得第二和第三項。
首先,我創建了一個.txt文件,該文件具有與您在原始.txt文件中輸入的相同的數據。 如您所知,我使用“ w”模式寫入數據。 我還創建了一個空列表,將用於存儲數據,然后寫入到output.txt文件中。
output_write = []
with open('test.txt', 'w') as file_object:
file_object.write('yellow.' + 'blue.' + 'purple.' + 'green')
file_object.write('\nred.' + 'blue.' + 'red.' + 'purple')
接下來,如您所知,我打開了創建的文本文件,並使用“ r”模式讀取了文件上的數據。 為了獲得所需的輸出,我在for循環中讀取文件的每一行,並針對每一行拆分該行以創建該行中項目的列表。 我根據每個項目('。')之間的時間段對它們進行拆分。 接下來,您要獲得行中的第二項和第三項,因此我創建了一個存儲index [1]和index [2]的變量,稱為new_read。 之后,我們將獲得所需的兩段數據,您很可能希望將其寫入輸出文件。 我將此數據存儲在一個名為output_data的變量中。 最后,我將輸出數據附加到我們先前創建的空列表中。
with open ('test.txt', 'r') as file_object:
for line in file_object:
read = line.split('.')
new_read = read[1:3]
output_data = (new_read[0] + '.' + new_read[1])
output_write.append(output_data)
最后,正如您前面提到的,我們可以將這些數據寫入名為“ output.txt”的文件中。
with open('output.txt', 'w') as file_object:
file_object.write(output_write[0])
file_object.write('\n' + output_write[1])
print(output_write[0])
print(output_write[1])
最后,我打印數據只是為了檢查輸出:
blue.purple
blue.red
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.