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个

  • 相关阅读:
    SQL Server 2016 Community Technology Preview 3.3
    orchard project 本地化
    Visual Studio Code
    Solidworks如何制作动画2
    Solidworks如何运行Toolbox
    Solidworks如何显示装饰螺纹线
    Solidworks如何将参考平面的图形投影到某曲面上
    Solidworks如何绘制装饰螺纹线
    Solidworks如何绘制文字
    SolidWorks如何绘制抽壳零件
  • 原文地址:https://www.cnblogs.com/myfy/p/11472558.html
Copyright © 2011-2022 走看看