Skip to main content
 首页 » 编程设计

python之如何让脚本遍历txt文件的每一行并执行一个功能

2024年10月01日7dudu

我正在尝试编写一个脚本,它遍历txt 文件 中的每个股票代码,并运行googlefinance 以收集它的所有历史数据并将其输出到 CSV 文件。我知道这不应该那么困难,但我似乎无法弄清楚这段代码中我做错了什么。它适用于第一只股票,然后崩溃。我假设它与 \n 有关,但我尝试了 splitlines() 函数和其他一些东西。

我的代码:

import datetime as dt 
import matplotlib.pyplot as plt 
from matplotlib import style 
from matplotlib.finance import candlestick_ohlc 
import matplotlib.dates as mdates 
import pandas as pd 
import pandas_datareader.data as web 
from googlefinance import getQuotes 
import json 
from datetime import datetime 
from forex_python.converter import CurrencyRates 
from yahoo_finance import Share 
 
sp500 = open('sp500tickers.txt').read().splitlines() 
 
for x in sp500: 
 
    share = Share(sp500[x]) 
    print (share.get_price()) 
 
    start = dt.datetime(2001,1,1) 
    end = dt.datetime(2017,1,1) 
 
    df = web.DataReader(share, 'google', start, end) 
    df.to_csv(''+x+'.csv', parse_dates=True, index_col=0) 

文本文件:

MMM 
ABT 
ABBV 
ACN 
ATVI 
AYI 
ADBE 
AAP 
AES 
AET 
AMG 
AFL 
A 
APD 
AKAM 
ALK 
ALB 
ALXN 
ALLE 
AGN 
ADS 
LNT 
ALL 
GOOGL 
GOOG 
MO 
AMZN 
AEE 
AAL 
... 

编辑后的代码:

with open('p1.txt', 'r') as f: 
    for line in f: 
        line = line.rstrip() 
 
        share = Share(line) 
        style.use('ggplot') 
        print (share.get_price()) 
 
        start = dt.datetime(2001,1,1) 
        end = dt.datetime(2017,1,1) 
 
        df = web.DataReader(share, 'google', start, end) 
        df.to_csv(''+line+'.csv', parse_dates=True, index_col=0) 

请您参考如下方法:

在您的for 循环 中,x 不是迭代器。 x 是值本身,因此更改此行:

share = Share(sp500[x]) 

到

share = Share(x) 

而对于读取文件,可以一次读取每一行,而不是一次读取所有,如下所示:

with open(file, 'r') as f: 
    for line in f: 
        line = line.rstrip() 
        #your code