2017-02-28 133 views
0

我寫了一個函數來創建動態文件,文件名將包含傳遞給函數的u 2參數。在python中創建動態文件名

def formrequests(carrier,airport): 
    s=requests.Session() 
    r=s.get("http://www.transtats.bts.gov/Data_Elements.aspx?Data=2") 
    soup=BeautifulSoup(r.text) 
    viewstate_element=soup.find(id="__VIEWSTATE") 
    viewstate=viewstate_element["value"] 
    eventvalidation_element=soup.find(id="__EVENTVALIDATION") 
    eventvalidation=eventvalidation_element["value"] 
    r = s.post("https://www.transtats.bts.gov/Data_Elements.aspx?Data=2", 
     data = (
      ("__EVENTTARGET", ""), 
      ("__EVENTARGUMENT", ""), 
      ("__VIEWSTATE", viewstate), 
      ("__EVENTVALIDATION", eventvalidation), 
      ("CarrierList", carrier), 
      ("AirportList", airport), 
      ("Submit", "Submit") 
     ) 
    ) 
    f=open("C:\\Users\\JAYASHREE\\Desktop\\Data Analyst Nanodegree\\Data Wrangking with MongoDB\\carrier-airport data files\\%s-%s.html","w" %(carrier,airport)) 
    f.write(r.text) 

當運行這個功能它扔我下面的錯誤:

TypeError         Traceback (most recent call last) 
<ipython-input-64-3323d46461b0> in <module>() 
     3 for carrier in carriers: 
     4  for airport in airports: 
----> 5   formrequests(carrier,airport) 

<ipython-input-63-258f8611f601> in formrequests(carrier, airport) 
    17     ("Submit", "Submit") 
    18     )) 
---> 19  f=open("C:\\Users\\JAYASHREE\\Desktop\\Data Analyst Nanodegree\\Data Wrangking with MongoDB\\carrier-airport data files\\%s-%s.html","w" %(carrier,airport)) 
    20  f.write(r.text) 

TypeError: not all arguments converted during string formatting 

請讓我知道如何解決這個問題。

回答

0

f=open格式字符串的行不正確。也許嘗試:

f=open("C:\\Users\\JAYASHREE\\Desktop\\Data Analyst Nanodegree\\Data Wrangking with MongoDB\\carrier-airport data files\\{0}-{1}.html".format(carrier,airport),"w") 

參數超出他們應該在的地方。

2

看起來你在該行上的格式不對。更改此:

f=open("C:\\Users\\JAYASHREE\\Desktop\\Data Analyst Nanodegree\\Data Wrangking with MongoDB\\carrier-airport data files\\%s-%s.html","w" %(carrier,airport)) 

這樣:

f=open("C:\\Users\\JAYASHREE\\Desktop\\Data Analyst Nanodegree\\Data Wrangking with MongoDB\\carrier-airport data files\\%s-%s.html" %(carrier,airport),"w")