python入门之文件基本操作
2020-06-30 14:35
274 查看
- 读文件
读全部文件
f = open("information","r",encoding="utf-8") #"r"表示只读 data = f.read() print(data)
读有限行文件
for i in range(2): print(f.readline())
循环读文件
for line in f : print(line.strip()) #strip()作用:去掉空格行
- 写文件
f = open("information","w",encoding="utf-8") #write覆盖原文件 f.write("\n你保护世界,我保护你") print(f.write())
- 追加文件
f = open("information","a",encoding="utf-8") #append向文件内追加内容,不覆盖原文件 f.write("\n你保护世界,我保护你")
- 文件中光标的位置
print(f.readline()) print(f.tell()) #查找文件中光标所在位置 f.seek(0) #文件中的光标位置回到初始位置 print(f.readline())
- 文件截断
f = open("information","r",encoding="utf-8") f.truncate(10)
- 读写(以读和追加的方式) “r+”
f = open("information","r+",encoding="utf-8") print(f.readline()) f.write("---------------------")
- 修改文件(需要两个文件,一个用来读,一个用来写,改好后的文件内容存入新文件中)
f = open("information","r",encoding="utf-8") f_new = open("information_new","w",encoding="utf-8") for i in f: if "太阳每天会照样升起" in i: i = i.replace("太阳每天会照样升起","太阳每天依然照样升起") f_new.write(i) f.close() f_new.close()
相关文章推荐
- Python爬虫入门 文件基本操作概况
- [Python ] python中文件的基本操作
- [Python ] python中文件的基本操作
- Python基础--基本文件操作
- [python]基本文件操作
- Python基础--基本文件操作
- Python中list(列表)、tuple(元组)、dict(字典)基本操作快速入门
- python3大文件解压和基本操作
- Python文件基本操作
- Python入门(十三) 文件操作
- python基本文件操作(文件输入和输出)
- Python文件基础操作(入门1)
- python中文件基本操作命令及注意事项
- python 基础之文件基本操作01
- python快速入门——python基本操作
- Python-csv文件基本操作
- python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
- Python入门笔记(15):对文件的操作(1)
- python入门教程、基本类型的操作及相互转换
- 小白学Python(二) 基本文件操作