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个

  • 相关阅读:
    (HDOJ 2503)a/b + c/d
    用VSTS进行网站压力测试
    .NET中IDisposable接口的基本使用
    创建ASP.Net自定义控件
    petshop4.0详解
    .net中SQL防注入代码
    petshop4 缓存机智在sql2005上的设置
    Asp.net自定义控件:概念
    .Net pet shop 4 和 MSMQ
    .net缓存自己总结的几条
  • 原文地址:https://www.cnblogs.com/myfy/p/11472558.html
Copyright © 2011-2022 走看看