为什么这个python脚本不会生成所需的文本文件? (尽管脚本运行没有错误)

时间:2014-07-03 04:41:12

标签: python

此脚本应生成股票价格值的文本文件。我似乎无法找到应该从此脚本生成的文本文件,或者让此脚本实际创建所需的文本文件...我添加了一段代码来检查文件是否存在,但是我继续得到文本文件确实没有创建的结果。请让我知道我可以做些什么来纠正。当我运行代码时,我没有得到任何错误。谢谢。

import urllib2
import time
import os
import sys

stockToPull = 'AAPL'

def pullData(stock):
    try:
        fileLine = stock+'.txt'
        urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
        sourceCode = urllib2.urlopen(urlToVisit).read()
        splitSource = sourceCode.split('\n')

        for eachLine in splitSource:
            splitLine = eachLine.split(', ')
            if len(splitLine)==6:
                if 'values' not in eachLine:
                    saveFile = open(fileLine,'a') 
                    lineToWrite = eachLine+'\n'
                    saveFile.write(lineToWrite)

        print 'Pulled', stock
        print 'sleeping'

        if os.path.isfile(fileLine): # checks to see if text file created
            print "file does exist"
        else:
            print "No such file"

        time.sleep(5) 

    except Exception, e:
        print 'main loop', str(e)

pullData(stockToPull)

3 个答案:

答案 0 :(得分:1)

您正在分割字符串', '上的每一行(请注意空格)。你应该只分享逗号:

for eachLine in splitSource:
    splitLine = eachLine.split(',')
    if len(splitLine)==6:
        # etc

最好打开文件一次,将每行写入文件,然后在完成后关闭文件。您可以使用with语句执行此操作:

with open(fileLine, 'w') as outfile:
    for eachLine in splitSource:
        splitLine = eachLine.split(',')
        if len(splitLine) == 6 and 'values' not in eachLine:
            outfile.write('%s\n' % eachLine)
    outfile.close()

答案 1 :(得分:0)

我认为您需要使用

检查数据是否到达
    from urllib2 import Request, urlopen, URLError, HTTPError
    fileLine = stock+'.txt'
    urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'

    try:
        response = urlopen(urlToVisit)
        sourceCode = response.read()
        <place your logic here>
    except HTTPError as e:
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code

    except URLError as e:
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason

你的代码工作正常

输出我

  ['uri:/instrument/1.0/AAPL/chartdata;type=quote;range=1y/csv', 'ticker:aapl', 'Company-Name:Apple Inc.', 'Exchange-Name:NMS', 'unit:DAY', 'timestamp:', 'first-trade:19801212', 'last-trade:20140702', 'currency:USD', 'previous_close_price:59.7843', 'Date:20130703,20140702', 'labels:20130703,20130801,20130903,20131001,20131101,20131202,20140102,20140203,20140303,20140401,20140501,20140602,20140701', 'values:Date,close,high,low,open,volume', 'close:59.2929,94.2500', 'high:60.1429,95.0500', 'low:58.6257,93.5700', 'open:59.0857,94.7300', 'volume:28420900,266380800', '20140620,90.9100,92.5500,90.9000,91.8500,100813200', .....
'20140702,93.4800,94.0600,93.0900,93.8700,28420900', '']
    ['uri:/instrument/1.0/AAPL/chartdata;type=quote;range=1y/csv']
    ['ticker:aapl']
    ['Company-Name:Apple Inc.']
    ['Exchange-Name:NMS']
    ['unit:DAY']
    ['timestamp:']
    ['first-trade:19801212']
    ['last-trade:20140702']
    ['currency:USD']
    ['previous_close_price:59.7843']
    ['Date:20130703,20140702']
    ['labels:20130703,20130801,20130903,20131001,20131101,20131202,20140102,20140203,20140303,20140401,20140501,20140602,20140701']
    ['values:Date,close,high,low,open,volume']
    ['close:59.2929,94.2500']
    ['high:60.1429,95.0500']
    ['low:58.6257,93.5700']
    ['open:59.0857,94.7300']
    ['volume:28420900,266380800']
    ['20130703,60.1143,60.4257,59.6357,60.1229,60232200']
    ['20130705,59.6314,60.4700,59.3357,60.0557,68506200']
    ['20130708,59.2929,60.1429,58.6643,60.0157,74534600']
    ......
    ['20140630,92.9300,93.7300,92.0900,92.1000,49482300']
    ['20140701,93.5200,94.0700,93.1300,93.5200,38170200']
    ['20140702,93.4800,94.0600,93.0900,93.8700,28420900']
    ['']
    Pulled AAPL
    sleeping
    file does exist

答案 2 :(得分:-1)

您的代码很好,但我不认为它能够做您想做的事情,或者您不知道自己想要什么。您还没有正确观察到您的数据。我对你的脚本做了一些小改动。请立即运行此脚本:

import urllib2
import time
import os
import sys

stockToPull = 'AAPL'

def pullData(stock):
    try:
        fileLine = stock+'.txt'
        urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
        sourceCode = urllib2.urlopen(urlToVisit).read()
        splitSource = sourceCode.split('\n')

        for eachLine in splitSource:
            splitLine = eachLine.split(', ')
            if len(splitLine)==6:
                print 'Entering outer'
                if 'values' not in eachLine:
                    print 'Entering innter'
                    saveFile = open(fileLine,'a')
                    lineToWrite = eachLine+'\n'
                    saveFile.write(lineToWrite)

        print 'Pulled', stock
        print 'sleeping'

        if os.path.isfile(fileLine): # checks to see if text file created
            print "file does exist"
        else:
            print "No such file"

        time.sleep(5)

    except Exception, e:
        print 'main loop', str(e)

pullData(stockToPull)

如果您注意到,我刚刚在实际写入文件的print块中放了两个if语句。在运行脚本时,我注意到print语句从未执行过。因此,根据我的知识,您的代码中没有错误,但它似乎并没有按照您的意愿行事。因此,请重新检查您的数据。

最后,为了解决这些问题,你必须使用代表Python Debugger的pdb库,这是一个非常有用的工具来调试你的代码而不会弄乱它。结帐video from PyCon