文件
概念:
文件的打开与关闭
用Python进行文件的读取操作,用Python内置函数open()打开一个文件,创建一个file对象,再进行相关操作。
语法格式:
file_object=open(file_name[,mode][,encoding="utf-8"][,buffering])
参数解释:
file_object:open()返回的文件对象;
file_name:要打开的文件,一般是文件的字符串值。
mode:文件的打开方式:只读,写入,追加等等。
encoding:制定文件的编码。一般使用
buffering:
文件的对象和属性
f.mode
f.closed
f=open("a.txt","r")
print(type(f))
print(f.name)
print(f.mode)
print(f.closed)
print(f.close())
print(f.closed)
<class ‘_io.TextIOWrapper’>
a.txt
r
False
None
True
文件的读写
1.读取的方式:
f.read():一次性读取所有的内容
with open("a.txt","r",encoding="utf-8") as f:
print(f.read()) #读用
I believe, for every drop of rain
that falls, A flower grows… (TXT文件里的内容)
f.readline():读取单独的一行
f=open("a.txt","r",encoding="utf-8")
f.readline() #读取第一行
'I believe, for every drop of rain\n'
f.readline() #读取第二行
'that falls, A flower grows...\n'
for i in range(2): #在上一次读完的基础上,接下去读两行
print(f.readline())
I believe, for every drop of rain #后两行内容
that falls, A flower grows...
f.readlines():以列表的形式返回文件的所有行
f.close()
f=open("a.txt","r",encoding="utf-8")
f.readlines()
['I believe, for every drop of rain\n', 'that falls, A flower grows...\n', 'I believe, for every drop of rain\n', 'that falls, A flower grows...\n', 'I believe, for every drop of rain\n', 'that falls, A flower grows...']
#要是含有/u3000,代表空格
2.f.write()
with open("test.txt","w",encoding="utf-8") as f:
f.write("传媒我爱你。")
#文件没有,就创建一个新的TXT文件内容为“传媒我爱你。”
with open("test.txt","w",encoding="utf-8") as f:
f.write("啦啦啦")
#如果文件已有,就修改覆盖新建TXT文件里的内容
在原有的内容后添加新的内容:
f=open("test.txt","a",encoding="utf-8")
f.write("再别康桥") #在缓存中
4 #返回字符长度
f.close() #关闭时,才真正写入
文件的定位读取
f.seek()
f.tell()
OS模块
这个模块提供一些执行文件处理操作的方法。
import os
os.rename("test.txt","test.md") #重命名
os.remove("b.txt") #删除文件
os.mkdir("test_file") #新建一个文件夹
os.getcwd() #返回当前进程的工作目录
'D:\\pycharm\\kc'
os.rmdir("test_file") #删除文件夹