如何跳过/删除行直到某个字符串

时间:2021-07-24 23:38:52

标签: python pandas string dataframe csv

我正在从 url (https://www.cboe.com/available_weeklys/get_csv_download/) 读取此 csv。我的问题是如何跳过所有行直到字符串“Available Weeklys - Exchange Traded Products (ETFs and ETNs)”。然而,它并不像skiprows=15 那样简单。我不能简单地跳过一定数量的行,因为字符串之前的行数将来可能会发生变化,所以我需要使用字符串作为停止点。谢谢!

1 个答案:

答案 0 :(得分:0)

我们可以将文件的内容读入一个字符串,计算新行的数量,直到遇到您的搜索字符串,并使用此计数动态跳过所需的行数。

import requests

# read contents of link into string variable
link = 'https://www.cboe.com/available_weeklys/get_csv_download/'
output = requests.get(link).text


find_str = "Available Weeklys - Exchange Traded Products (ETFs and ETNs)"
# find index of search string in output
idx = output.find(find_str)
# Count number of newlines until search string is encountered
skiprows_val = output[:idx+len(find_str)].count("\n")
print(skiprows_val)

df = pd.read_csv(link, skiprows = skiprows_val)
df
相关问题