前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python创建txt文件

python创建txt文件

作者头像
py3study
发布2020-01-07 20:01:03
4.6K0
发布2020-01-07 20:01:03
举报
文章被收录于专栏:python3

1.自己写入txt

直接上核心代码:

代码语言:javascript
复制
with open("douban.txt","w") as f:
        f.write("这是个测试!")1212

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

结果就是这样:

这里写图片描述
这里写图片描述

2.将文件输入(print)的内容写入txt

代码语言:javascript
复制
#分模块测试,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,至于那个分割线问题,因为后续写入和前面已经有的会混在一块,所以我做分割用:

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

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

这里写图片描述
这里写图片描述

That’s all

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.自己写入txt
  • 比较常用MODE
  • 不清空连续写入
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档