![](/img/trans.png)
[英]Read a file and extract data and assign to a variable from a python file
[英]read | deliminator file and extract variable in Python
我正在嘗試使用分隔符“ |”讀取txt文件,然后提取第二個和第三個變量。 因此數據如下所示:
a|bb|cc|
aaa|b|cccc|
我想只用第二和第三個變量創建數據:
bb cc
b cccc
有什么建議么?
謝謝!
with open("data.txt") as f:
for line in f:
col2, col3 = line.split('|')[1:3] # get 2nd and 3rd column
print col2, col3 # this could be written to a file if needed
會給你
bb cc
b cccc
其中data.txt
是您的數據文件。
說明 :
您逐行讀取文件,並用|
分隔每一行|
定界符,並在每行上打印2nd和3rd元素。 該數據也可以寫入文件或進一步處理。
使用csv
模塊
import csv
input = csv.reader(open('your_file.txt', 'rb'),delimiter="|")
for row in input:
print row[1:]
這將打印出第一行以外的每一行中的其他每個值。 當然,您會做任何您想做的處理,而不是在我打印的地方進行。
將csv
模塊與適當的方言配合使用,然后每行對結果列表進行切片並輸出。
您可以使用csv模塊。 簡潔大方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.