スクリプトを1ファイルにロードするような方法でループさせようとしていましたが、ファイル2を出力するには、出力ファイル1の値を消去してから再読み込みを開始し、値が下がっている場合は値を出力2に移動します(古いものを上書きします)。"Unboundlocalerror:ローカル変数" Val "代入前に参照された"エラー
私はこれまでにかなり成功していますし、スクリプトに追加するその他のものを知らず、なぜ私が "Unboundlocalerror:Local Variable" Val "Assigning Before Reassced Before Assignment"私は非常に小さな入力ファイルを持っているときに、ローディングプロセスは、私が望む方法を実行します。
私はそのエラーを修正するために私のスクリプトを変更する方法を知っている人、私はなぜ起こっているが理解できませんでした。
私は徹底的に調査しようとしましたが、私が見つけた提案はどれもうまくいきませんでした(または私は間違って実装しました。私はスクリプトを添付しました)。
import urllib2,re,urllib,urlparse,csv,sys,time,threading,codecs,shutil
from bs4 import BeautifulSoup
def extract(url):
try:
sys.stdout.write('0')
# global file
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
product = soup.find("div", {"class": "js-product-price"})
price = product.findNext('div',{'class': 'js-price-display'}).getText().strip()
oos = product.findNext('p', attrs={'class': "price-oos"})
if oos is None:
oos = 'In Stock'
else:
oos = oos.getText()
val = url + "," + price + "," + oos + "," + time.ctime() + '\n'
# ifile.write(val)
sys.stdout.write('1')
except Exception as e:
print e
return val
while True:
ifile = open('output.csv', "w", 0)
inputs = csv.reader(open('input.csv'))
# inputs = csv.reader(codecs.open('input.csv', 'rU', 'utf-16'))
ifile.write('URL' + "," + 'Price' + "," + 'Stock' + "," + "Time" + '\n')
for i in inputs:
ifile.write(extract(i[0]))
ifile.close()
更新:ヘルプみんなのため
ありがとう!私は今、エラーを取得しています上記のスクリプトでは
import urllib2,re,urllib,urlparse,csv,sys,time,threading,codecs,shutil
from bs4 import BeautifulSoup
def extract(url):
try:
sys.stdout.write('0')
# global file
page = urllib2.urlopen(url).read()
soup = BeautifulSoup(page, 'html.parser')
product = soup.find("div", {"class": "js-product-price"})
price = product.findNext('div',{'class': 'js-price-display'}).getText().strip()
oos = product.findNext('p', attrs={'class': "price-oos"})
if oos is None:
oos = 'In Stock'
else:
oos = oos.getText()
val = url + "," + price + "," + oos + "," + time.ctime() + '\n'
# ifile.write(val)
sys.stdout.write('1')
except Exception as e:
print e
else:
return val
while True:
ifile = open('output.csv', "w", 0)
inputs = csv.reader(open('input.csv'))
# inputs = csv.reader(codecs.open('input.csv', 'rU', 'utf-16'))
ifile.write('URL' + "," + 'Price' + "," + 'Stock' + "," + "Time" + '\n')
for i in inputs:
val_to_write = extract(i[0])
if val_to_write:
ifile.write(val_to_write)
ifile.close()
shutil.copy('output.csv', 'output2.csv')
print("finished")
:「とValueError:I/Oオペレーション閉じられたファイルの」これが私の新しいスクリプトです。ありがとう
は、お返事ありがとうございました! !私は今それを試しています。私は年齢のためにこれに取り組んできました。大いに感謝します – Pythonhelpneeded
ちょっと、私はそれに渦を吹き込みました。そして今、私は "ValueError:閉じたファイルのI/O操作"を1〜 – Pythonhelpneeded
'while True'ループ内でファイルを' open'して 'close'しないでください。 – DeepSpace