生活随笔
收集整理的這篇文章主要介紹了
python创建txt文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.自己寫入txt
直接上核心代碼:
with?open("douban.txt","w")?as?f:f.write("這是個測試!")1212
這句話自帶文件關閉功能,所以和那些先open再write再close的方式來說,更加pythontic!
結果就是這樣:
2.將文件輸入(print)的內容寫入txt
#分模塊測試,txt寫入測試#?-*-?coding:?utf-8?-*-from?selenium?import?webdriverimport?selenium.webdriver.support.ui?as?uiimport?time#driver_item=webdriver.Firefox()driver_item=webdriver.PhantomJS(executable_path="phantomjs.exe")
url="https://movie.douban.com/subject/3541415/?tag=%E7%A7%91%E5%B9%BB&from=gaia_video"wait?=?ui.WebDriverWait(driver_item,10)
driver_item.get(url)try:driver_item.find_element_by_xpath("//img[@class='bn-arrow']").click()????#wait.until(lambda?driver:?driver.find_element_by_xpath("//div[@class='review-bd']/div[2]/div/div"))time.sleep(1)comments_deep?=?driver_item.find_element_by_xpath("//div[@class='review-bd']/div[2]/div")????print?u"深度長評:"+comments_deep.text????#print?type(comments_deep.text)#<type?'unicode'>comments_wr=comments_deep.text.encode('utf-8')????#print?type(comments_wr)#<type?'str'>#title="盜夢空間"#中文命名文件名亂碼,內容可用????title="Inception"with?open("%s.txt"%title,"w")?as?f:#格式化字符串還能這么用!for?i?in?comments_wr:f.write(i)except:????print?'can?not?caught?the?comments!'123456789101112131415161718192021222324252627282930123456789101112131415161718192021222324252627282930
比較常用MODE
不清空連續寫入
沒有文件時候會自動創建的,但是!如果我重新對此進行寫入,那么會先清空,然后再寫,就是說以前寫的沒了,這樣搞不好吧,我可是要記錄很多東西的啊,萬能的a出現了。。。
把核心代碼改成這樣就可以了,記得把w改成a,至于那個分割線問題,因為后續寫入和前面已經有的會混在一塊,所以我做分割用:
with?open("%s.txt"%title,"a")?as?f:#格式化字符串還能這么用!f.write("\n-------------------------------------我是分割線-----------------------------------------\n")????????for?i?in?comments_wr:f.write(i)12341234
效果是這樣的,不夠好看自己再加細節,比如換行多幾次
That’s all
轉載于:https://blog.51cto.com/huangmanyao/1968005
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的python创建txt文件的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。