[英]How to iterate through rows in a file which is stored in a variable python
我有一個 html 形式的解碼文件存儲在一個變量中:
file_data = file.read().decode('utf-8')
print(file_data)
我想用一個跟蹤行號的計數器遍歷文件,以便我可以獲得表開始時的行號。 這是我嘗試過的兩種方法:
方法一:
counter = 0
for row in file_data:
if row == 'Date,Unique Id,Tran Type,Cheque Number,Payee,Memo,Amount':
date_line_no = counter
break
counter += 1
方法二:
for line, row in enumerate(file_data):
first_column = row[0]
if first_column == 'Date':
print(row)
date_line_no = line
我理想的 output 將是 7,因為那是表格從其列開始的時候。
使用enumerate
function,然后搜索包含逗號的行,如果它確實用逗號分隔,然后繼續您當前的方式。 從文件中讀取時,您還應該使用with
語句。 這避免了必須立即讀取整個文件並確保它在最后正確關閉文件。
例如:
with open(filename) as file:
for i,row in enumerate(file):
if ',' in row and row.split(',')[0] == 'Date':
break
print(i) # output is the index of the header row.
如果您必須以自己的方式打開文件,那么它仍然是相同的,除了您還需要將整個文件拆分為\n
。
file_data = file.read().decode('utf-8')
print(file_data)
for i, row in enumerate(file_data.split('\n')):
if ',' in row and row.split(',')[0] == 'Date':
break
print(i)
# Opening the file
file = open('your_file_name_or_location')
# adding a counter for each line
for index, content in enumerate(file):
var = content.split(',') # Spliting each line by ','
if var[0] == 'date':
break # Getting out of loop if first element is 'date'
print(index + 1) # Position of header of the table
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.