首页 > 文章列表 > python如何处理文件

python如何处理文件

python文件
336 2022-08-07

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、文件的读和写

open()用于读取或写入的文件并返回文件句柄,这个句柄提供了读取或写入文件数据的方法。

with open('data.txt', 'w') as f:
    data = 'some data to be written to the file'
f.write(data)

2、获取文件列表

文件名称有匹配模式。假设我们想在目录中找到所有.txt文件,可以使用glob()来实现。glob()方法创建了一个生成器,允许我们迭代。

>>> txt_files = list(Path('.').glob("*.txt"))
... print("Txt files:", txt_files)
...
Txt files: [PosixPath('hello_world.txt'), PosixPath('hello.txt')]