发布时间:2026-07-21阅读(0)
1. 创建文件/打开文件,接下来我们就来聊聊关于python创建文件打开文件读写文件?以下内容大家不妨参考一二希望能帮到您!

python创建文件打开文件读写文件
Python笔记 创建、打开、编辑、读取、删除文件1. 创建文件/打开文件
用open()创建或者打开文件并创建一个文件对象,用close()关闭文件,文件打开后一定要关闭。
In [1]:
f = open(Python笔记 文件读写.txt, w) #以w模式打开Python笔记 文件读写.txt,如果文件存在则清空文件打开,如果文件不存在就创建一这个文件
In [2]:
print (f)<_io.TextIOWrapper name=Python笔记 文件读写.txt mode=w encoding=cp936>
In [3]:
f.close()
In [4]:
f.closed
Out[4]:
True
2. 用with open() as f: 安全打开文件
用with open() as file: 语句打开文件,会自动在打开文件后关闭文件,不用手动关闭,比较安全。但必须保证文件存在,否则出错。
In [5]:
f = open(Python笔记 文件读写with-as.txt,w)with open(Python笔记 文件读写with-as.txt) as f: data = f.read()
In [6]:
data
Out[6]:
In [7]:
f.closed
Out[7]:
True
3. 写文件 f.write()
用f.write()向已打开的文件中写入字符串,返回写入的字符数。写之前文件须打开。
In [8]:
f = open(Python笔记 文件读写write.txt,w)
In [9]:
f.write(这是第一行\n)
Out[9]:
python 文件操作
Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图