Python 文件处理

BBigSun 评论216阅读模式

打开文件

打开文件,就必须关闭文件:

file = open('hello.py', 'w')
print(file.name)
print(file.mode)
print(file.closed)
file.close()

详情查看:https://www.runoob.com/python/file-methods.html文章源自十年又十年-https://www.bbigsun.com/463.html

语法:文章源自十年又十年-https://www.bbigsun.com/463.html

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:文章源自十年又十年-https://www.bbigsun.com/463.html

  • file: 必需,文件路径(相对或者绝对路径)。
  • mode: 可选,文件打开模式
  • buffering: 设置缓冲
  • encoding: 一般使用utf8
  • errors: 报错级别
  • newline: 区分换行符
  • closefd: 传入的file参数类型
  • opener: 设置自定义开启器,开启器的返回值必须是一个打开的文件描述符。

with 语句

使用 with 语句会自动帮我们关闭文件,推荐使用这种方法。文章源自十年又十年-https://www.bbigsun.com/463.html

with open('hello.py', 'w') as fo:
    print(fo.name)
  • fo: file object 文件对象
  • fp: file point 文件指针
  • fd: file description 文件描述符

File 的常用方法

  • write() 方法可将任何字符串写入一个打开的文件。write()方法不会在字符串的结尾添加换行符('\n')
  • read() 方法从一个打开的文件中读取一个字符串。
  • tell()方法告诉你文件内的当前位置。
  • seek(offset [,from]) 方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。

Python os 模块

详情查看:https://www.runoob.com/python/os-file-methods.html文章源自十年又十年-https://www.bbigsun.com/463.html 文章源自十年又十年-https://www.bbigsun.com/463.html

纸上得来终觉浅,绝知此事要躬行。

weinxin
17688689121
我的微信
微信扫一扫
Python最后更新:2024-5-11
BBigSun
  • 本文由 BBigSun 发表于 2023年 4月 19日 08:51:37
  • 转载请务必保留本文链接:https://www.bbigsun.com/463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定