zoukankan      html  css  js  c++  java
  • Python_文件相关操作

    1.open(filePath,type)方法:打开文件

      filePath:文件路径

      type:操作文件的方式(r:读取,w:覆盖写入,a:追加写入)

    2.strip()方法:去除读取到的每行内容后的换行符

    stream = open('E:/projects/Python/test/fileopen.txt','r') #读取
    
    print('打印一下原文件中的内容.....')
    for line in stream:
        print(line.strip()) #strip()方法可以去除结尾的换行符
    stream.close()
    
    stream = open('E:/projects/Python/test/fileopen.txt','w') #写入,写入参数为w时,写入会覆盖原有内容
    stream.write('Lucky:11个
    ')
    stream.close()
    
    print('打印一下使用w写入后的文件内容.....')
    stream = open('E:/projects/Python/test/fileopen.txt','r') #读取
    for line in stream:
        print(line.strip()) #strip()方法可以去除结尾的换行符
    stream.close()
    
    stream = open('E:/projects/Python/test/fileopen.txt','a') #写入,写入参数为a时,写入不会覆盖原有内容,而是追加写入
    stream.write('Baby:11个
    ')
    stream.close()
    
    print('打印一下使用a写入后的文件内容.....')
    stream = open('E:/projects/Python/test/fileopen.txt','r') #读取
    for line in stream:
        print(line.strip()) #strip()方法可以去除结尾的换行符
    stream.close()

    执行结果:

    打印一下原文件中的内容.....
    张三:5个
    李四:10个
    王五:20个
    打印一下使用w写入后的文件内容.....
    Lucky:11个
    打印一下使用a写入后的文件内容.....
    Lucky:11个
    Baby:11个

  • 相关阅读:
    CSS3实现轮播切换效果
    angularjs directive
    angularjs 迭代器
    anjularjs 路由
    sublime text3 快捷键设置
    如何使用git 跟进项目进程
    hdu 4842(NOIP 2005 过河)之 动态规划(距离压缩)
    叠箱子问题 之 动态规划
    华为oj 之 蜂窝小区最短距离
    华为oj 之 整数分隔
  • 原文地址:https://www.cnblogs.com/myfy/p/11472558.html
Copyright © 2011-2022 走看看