文件处理
小试牛刀
文件句柄=open(文件路径,mode=文件的打开模式,encoding=字符编码)
with open('aaa.txt',mode='r',encoding='utf-8') as f:
print(f.readable())
print(f.read())
f.closed
>>>True
>>>你好,世界之窗
该地方采用相对路径,若采用绝对路径,需要加转义符r
默认就是mode=r 只读
以上操作涉及两方面的资源
- 操作系统需要打开文件
- f就是一个python 的变量
Character | Detail
---|---
r | open for reading (default)
w | open for writing, truncating the file first
a| open for writing, appending to the end of the file if it exists
b| binary mode
t|text mode (default)
+|open a disk file for updating (reading and writing)
U|universal newline mode (for backwards compatibility; should not be used in new code)
文件的打开模式
默认为文本模式
r: 默认的打开模式,只读模式,文件如果不存在则报错
w: 只写模式,不可读,不存在则创建,存在则清空内容复写
a:只追加写模式,(写模式的一种)不可读,不存在则创建,存在则只追加内容,不复写。指针直接到末尾,通常用于记录log
with open ('aaa.txt',mode='r',encoding='utf-8') as f:
print(f.readline()) #只读一行,并把光标移动到下一行的首位置,可连续放n行可以读取n行数据
print(f.readlines()) #将文件内容全部读出并放于列表内
>>>你好,
>>>
>>>['你好,\n', '世界之窗\n', '我来了']
with open('111.txt',mode='w',encoding='utf-8') as f:
f.write('hello')
print(f.writable())
L=['bruce',"said,he couldn't be caged"]
print(f.writelines(L))
with open('222.txt',mode='a',encoding='utf-8') as f:
print(f.readable())
print(f.writable())
f.write('你好\n 这世界,我来了')
a 写模式的一种,
非文本模式(b模式,即二进制)
比如mp3,mp4,jpg等格式,只能用b模式,b表示以字节的方式操作,无需考虑字符编码。以b方式打开时,读取的内容是字节类型,写入时也需要提供字节类型,不能指定编码
with open('4.jpg',mode='rb') as f:
print(f.readable())
print(f.writable())
print(f.read())
>>True
>>>False
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】
w+,写读【可读,可写】
a+, 写读【可读,可写】