• Python入门系列(十)一篇学会python文件处理


    文件处理

    在Python中处理文件的关键函数是open()函数。有四种不同的方法(模式)来打开一个文件

    "r" - 读取 - 默认值。打开一个文件进行读取,如果文件不存在则出错。

    "a" - Append - 打开一个文件进行追加,如果文件不存在则创建该文件

    "w" - 写 - 打开一个文件进行写入,如果不存在则创建文件

    "x" - 创建 - 创建指定的文件,如果文件存在则返回错误。

    此外,你还可以指定文件应以二进制或文本模式处理。

    "t" - 文本 - 默认值。文本模式

    "b" - 二进制 - 二进制模式(如图像)。

    要打开一个文件进行阅读,只需指定文件的名称即可

    f = open("demofile.txt")
    

    上面的代码与

    f = open("demofile.txt", "rt")
    

    因为 "r "代表读取,"t "代表文本,是默认值,你不需要指定它们。

    注意:确保该文件存在,否则你会得到一个错误。

    读取文件

    open()函数返回一个文件对象,它有一个read()方法用于读取文件的内容

    f = open("demofile.txt", "r")
    print(f.read())
    

    如果文件位于一个不同的位置,你将不得不指定文件路径,像这样

    f = open("D:\\myfiles\welcome.txt", "r")
    print(f.read())
    

    只读文件的部分内容

    f = open("demofile.txt", "r")
    print(f.read(5))
    

    读取行

    f = open("demofile.txt", "r")
    print(f.readline())
    

    通过调用readline()两次,您可以读取前两行

    f = open("demofile.txt", "r")
    print(f.readline())
    print(f.readline())
    

    通过遍历文件的各行,您可以逐行读取整个文件

    f = open("demofile.txt", "r")
    for x in f:
      print(x)
    

    最好总是在处理完文件后将其关闭。

    f = open("demofile.txt", "r")
    print(f.readline())
    f.close()
    

    注意:您应该始终关闭您的文件,在某些情况下,由于缓冲,在您关闭文件之前,可能不会显示对文件所做的更改。

    写入文件

    要写入现有文件,必须向open()函数添加参数

    "a" - 附加 - 将附加到文件的末尾。

    "w" - 写 - 将覆盖任何现有内容

    f = open("demofile2.txt", "a")
    f.write("Now the file has more content!")
    f.close()
    
    #open and read the file after the appending:
    f = open("demofile2.txt", "r")
    print(f.read())
    
    f = open("demofile3.txt", "w")
    f.write("Woops! I have deleted the content!")
    f.close()
    
    #open and read the file after the appending:
    f = open("demofile3.txt", "r")
    print(f.read())
    

    注意:"w "方法将覆盖整个文件。

    要在Python中创建一个新的文件,使用open()方法,并带有以下参数之一

    "x" - 创建 - 将创建一个文件,如果该文件存在则返回错误

    "a" - 附加 - 如果指定的文件不存在将创建一个文件

    "w" - 写 - 如果指定的文件不存在,将创建一个文件

    f = open("myfile.txt", "w")
    

    删除文件

    要删除一个文件,你必须导入OS模块,并运行其os.remove()函数

    import os
    os.remove("demofile.txt")
    

    检查文件是否存在

    import os
    if os.path.exists("demofile.txt"):
      os.remove("demofile.txt")
    else:
      print("The file does not exist")
    

    要删除整个文件夹,使用os.rmdir()方法

    import os
    os.rmdir("myfolder")
    

    注意:你只能删除空文件夹。

    您的关注,是我的无限动力!

    公众号 @生活处处有BUG

  • 相关阅读:
    c++类与对象
    【java】使用springMVC优雅的响应数据
    C++11之可变参数模板
    就瞎写=感想
    一步步带你用react+spring boot搭建后台之二(登录与首页篇)
    中文GPTS详尽教程,字节扣子Coze插件使用全输出
    外贸SOHO新手指南来了!六大注意事项!
    跑通yolox-s官方源码(可与yolov5s做对比试验)
    操作系统原理
    Spring Boot 自定义Jackson ObjectMapper,你学会了吗?时间 2022-06-27 08:28:49 51CTO 开发
  • 原文地址:https://www.cnblogs.com/bugs-in-life/p/16659305.html