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()

    谢土豪

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

  • 相关阅读:
    WebService
    jdbc访问数据库
    ssm文件配置
    ssh文件配置
    配置数据源的三种方式和sql心跳的配置
    SQL in与exists
    套接字
    oracle 方向及资料
    ORACLE恢复数据
    SQL时间戳的使用
  • 原文地址:https://www.cnblogs.com/kerwinC/p/5929381.html
Copyright © 2011-2022 走看看