zoukankan      html  css  js  c++  java
  • Python文件操作

    读写文件

    f = open("test.txt","r",encoding='utf-8')
    data = f.read()
    print(data) f
    = open("test.txt","w",encoding='utf-8')#写入,是通过创建新文件的方式,如果有重复的名字的文件,会清空旧的内容。 f.write("呵呵哒 ")# 是换行符
    f.close()#关闭文件

    追加文件

    f = open("test.txt","a",encoding='utf-8')
    f.write("呵呵哒")
    f.close()

    逐行读文件

    # Cheng
    f = open("test.txt","r",encoding='utf-8')
    print(f.readline())#读一行
    f.close()
    f = open("test.txt","r",encoding='utf-8')
    for i in range(5):  #读五行
        print(f.readline())
    f.close()

    另一种方式readlines

    首先看一下readlines输出的内容是什么样子

    它会把文件内容转化为一个列表。

    接下来我们输出想要的内容

    # Cheng垃圾的写法
    f = open("test.txt","r",encoding='utf-8')
    count = 0
    for line in f.readlines():
        if count <= 9:#取出前十行
            print(line.strip())
            count += 1
        else:
            exit()
    f.close()

    注意:这么读小文件没事,读大文件需要先把文件存到内存中,会导致程序卡死。

    高级写法(迭代器)#

    # Cheng
    f = open("test.txt","r",encoding='utf-8')
    count = 0
    for line in f:#因为文件指针不会往回走,所以也是逐行。
        if count <= 9:
            print(line)
            count += 1
        else:
            exit()
    f.close()

    谢土豪

    如果有帮到你的话,请赞赏我吧!

  • 相关阅读:
    宝塔nginx配置
    宝塔apache配置
    公司代码规范
    发送短信倒计时
    js layui 分页脚本
    常用mysql
    win10子系统ubuntu下安装nodejs,并使用n管理版本
    Cocos Creator 热更新文件MD5计算和需要注意的问题
    android app 闪屏
    关于模板测试几个问题
  • 原文地址:https://www.cnblogs.com/kerwinC/p/5929381.html
Copyright © 2011-2022 走看看