python文件操作
读写文件是最常见的IO操作。Python内置了读写文件的函数,用法和C是兼容的。
读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘,所以,读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据(读文件),或者把数据写入这个文件对象(写文件)。
下面将介绍下在python下文件常见的读写操作:
1、文件读写操作:
f = open("文件","模式"[,“编码”]) #打开文件
f.read()等操作方法 #操作文件
f.close() #关闭文件
上面操作文件的方法比较繁琐,会经常忘记关闭文件;所以可以通过with
语句来自动帮我们调用close()
方法:
) as f:
f.read()等操作方法
2、文件操作模式:
常规模式:
- r :只读模式;以读方式打开文件,只可读取文件信息,不能写入。
- w:只写模式;不可读,文件不存在则创建;如文件存在,则清空该文件,再写入新内容。
- a:追加模式;可读写,文件不存在则创建;如文件存在则在文件末尾追加新内容。
'+'模式,表示可以同时读写某个文件:
- r+:可读可写,不会创建不存在的文件。如果直接写文件,则从顶部开始写,覆盖相同字节数的内容,如果先读后写,则会在文件最后追加内容;或先写后读也会在文件最后追加内容。
#先写后读文件
#!/usr/bin/env python3
import os
with open("/tmp/file.txt","r+") as f:
f.write("hello world!!\n")
for i in f.readlines():
print(i.strip())
执行结果:
[root@localhost tmp]# ./pytest20.py
hello world!!
[root@localhost tmp]# ./pytest20.py
hello world!!
hello world!!
#先读后写文件
#!/usr/bin/env python3
import os
with open("/tmp/file.txt","r+") as f:
f.readline()
f.write("hello world!!\n")
os.system("cat /tmp/file.txt")
执行结果:
[root@localhost tmp]# ./pytest20.py
hello world!!
[root@localhost tmp]# ./pytest20.py
hello world!!
hello world!!
[root@localhost tmp]# ./pytest20.py
hello world!!
hello world!!
hello world!!
#直写文件
#!/usr/bin/env python3
import os
print("文件原始内容:")
os.system("cat /tmp/file.txt")
print("\r")
with open("/tmp/file.txt","r+") as f:
f.write("hello world!!\n")
print("文件修改后内容:")
os.system("cat /tmp/file.txt")
执行结果:
文件原始内容:
what fuck!!! Are you OK?
文件修改后内容:
hello world!!
re you OK?
- View Code
- w+ 可读可写 如果文件存在 则覆盖整个文件不存在则创建
- a+ 可读可写 从文件顶部读取内容 从文件底部添加内容 不存在则创建
U模式:
- 'U':表示在读取时,可以将\r\n自动转换为\n(与r或r+模式使用)
b模式:
- 'b':表示处理二进制文件(linux可忽略,windows处理二进制文件时需标注)
3、文件对象的操作方法:
- f.read():读取文件所有内容;也可以读取指定多少个字符:f.read(num),num为指针
#读取文件所有内容
#!/usr/bin/env python3
import os
with open("/tmp/file.txt","r+") as f:
print(f.read().strip())
执行结果:
[root@localhost tmp]# cat file.txt
hello world!!
re you OK?
[root@localhost tmp]# ./pytest20.py
hello world!!
re you OK?
#读取指定指针的字符
#!/usr/bin/env python3
import os
with open("/tmp/file.txt","r+") as f:
print(f.read(5)) #指针指向5,所以只读取5个字符
执行结果:
[root@localhost tmp]# cat file.txt
hello world!!
re you OK?
[root@localhost tmp]# ./pytest20.py
hello
- View Code
- f.readline():读取一行内容
#!/usr/bin/env python3
with open("/tmp/file.txt","r") as f:
print(f.readline().strip())
执行结果:
[root@localhost tmp]# cat file.txt
hello world!!
re you OK?
[root@localhost tmp]# ./pytest20.py
hello world!!
- f.seel():指定文件中指针位置,读取文件时,指针前的内容将不会被显示
#!/usr/bin/env python3
with open("/tmp/file.txt","r") as f:
f.seek(5)
print(f.readline().strip())
执行结果:
[root@localhost tmp]# cat file.txt
hello world!!
re you OK?
[root@localhost tmp]# ./pytest20.py
world!!
- f.tell():获取指针位置
#!/usr/bin/env python3
with open("/tmp/file.txt","r") as f:
print(f.tell())
print(f.readline().strip())
print(f.tell())
执行结果:
[root@localhost tmp]# cat file.txt
hello world!!
re you OK?
[root@localhost tmp]# ./pytest20.py
0
hello world!!
1
f.truncate():截取指定大小的文件内容,仅保留指定之前数据(会写入源文件)
#!/usr/bin/env python3
with open("/tmp/test_file","r") as f:
f.truncate(1024) #截取1024字节即1K数据
执行结果:
[root@localhost tmp]# ls -lh test_file
-rw-r--r--. 1 root root 1.7K Jun 26 18:57 test_file
[root@localhost tmp]# ./pytest20.py
[root@localhost tmp]# ls -lh test_file
-rw-r--r--. 1 root root 1.0K Jun 26 18:58 test_file
- f.readable():判读文件是否可读
#!/usr/bin/env python3
with open("/tmp/test_file","r") as f:
print(f.readable())
with open("/tmp/test_file","w") as f:
print(f.readable())
执行结果:
True #返回True表示可读
False #返回False表示不可读
- f.writeable():判读文件是否可写,同f.readable()判读方式差不多,这里不多介绍
- f.write(str):将字符串str写入文件
#!/usr/bin/env python3
with open("/tmp/test_file","w") as f:
f.write("hello linux!\nhello python!")