1.自己写入txt

直接上核心代码:

with open("douban.txt","w") as f:
        f.write("这是个测试!")1212

这句话自带文件关闭功能,所以和那些先open再write再close的方式来说,更加pythontic!

结果就是这样:

python创建txt文件

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

python创建txt文件


不清空连续写入

没有文件时候会自动创建的,但是!如果我重新对此进行写入,那么会先清空,然后再写,就是说以前写的没了,这样搞不好吧,我可是要记录很多东西的啊,万能的a出现了。。。

把核心代码改成这样就可以了,记得把w改成a,至于那个分割线问题,因为后续写入和前面已经有的会混在一块,所以我做分割用:

with open("%s.txt"%title,"a") as f:#格式化字符串还能这么用!
        f.write("\n-------------------------------------我是分割线-----------------------------------------\n")        for i in comments_wr:
            f.write(i)12341234

效果是这样的,不够好看自己再加细节,比如换行多几次

python创建txt文件


That’s all