一、环境
环境 | 版本 |
---|---|
操作系统 | CentOS 7.9.2009 |
Python | 3.9.7 |
二、打开、关闭
使用 open()
函数打开文件。open()
函数需要两个参数,第一个参数是文件路径或文件名,第二个是文件的打开模式。
打开模式通常是下面这样的:
"r"
,以只读模式打开,你只能读取文件但不能编辑/删除文件的任何内容,默认的模式"w"
,以写入模式打开,如果文件存在将会删除里面的所有内容,然后打开这个文件进行写入"a"
,以追加模式打开,写入到文件中的任何数据将自动添加到末尾"b"
,以二进制的方式打开
使用 close()
关闭文件,如果不关闭会持续占用一些内存和操作系统资源,不关闭的文件也有可能造成数据丢失,重复关闭不会有任何影响。
脚本 2.py
#!/usr/bin/env python3
userlist = open('/etc/passwd','r')
userlist.close()
三、读取
使用 read()
可以一次性读取整个文件的内容到字符串:
脚本 3.1.py
#!/usr/bin/env python3
userlist = open('/etc/passwd','r')
print(userlist.read())
userlist.close()
[root@localhost 5]# python3 3.1.py
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
*****
在处理文本文件的时候,我们通常会采用逐行处理,readline()
就是用来每次读取文件的一行,readlines()
可以读取所有行,但不同于 read()
,这个函数返回的是一个列表,列表中每个元素都是对应文本文件中一行内容的字符串。
脚本 3.2.py
#!/usr/bin/env python3
userlist = open('/etc/passwd','r')
print(userlist.readline())
print(userlist.readlines())
userlist.close()
[root@localhost 5]# python3 3.2.py
root:x:0:0:root:/root:/bin/bash
['bin:x:1:1:bin:/bin:/sbin/nologin\n', 'daemon:x:2:2:daemon:/sbin:/sbin/nologin\n', 'adm:x:3:4:adm:/var/adm:/sbin/nologin\n', 'lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin\n', 'sync:x:5:0:sync:/sbin:/bin/sync\n', 'shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown\n', 'halt:x:7:0:halt:/sbin:/sbin/halt\n', 'mail:x:8:12:mail:/var/spool/mail:/sbin/nologin\n', 'operator:x:11:0:operator:/root:/sbin/nologin\n', 'games:x:12:100:games:/usr/games:/sbin/nologin\n', 'ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin\n', 'nobody:x:99:99:Nobody:/:/sbin/nologin\n', 'systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin\n', 'dbus:x:81:81:System message bus:/:/sbin/nologin\n', 'polkitd:x:999:998:User for polkitd:/:/sbin/nologin\n', 'sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin\n', 'postfix:x:89:89::/var/spool/postfix:/sbin/nologin\n', 'chrony:x:998:996::/var/lib/chrony:/sbin/nologin\n', 'tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin\n']
四、写入
最常用的写入文件的方法是 write()
,让我们通过 write()
方法打开一个文件然后我们随便写入一些文本。
脚本 4.1.py
#!/usr/bin/env python3
# 写入
testfile = open('/root/testfile.txt','w')
testfile.write('hello')
testfile.write('word')
testfile.close()
# 读取
testfile = open('/root/testfile.txt','r')
print(testfile.readlines())
testfile.close()
[root@localhost 5]# python3 4.1.py
['helloword']
追加写入,防止覆盖原内容
脚本 4.2.py
#!/usr/bin/env python3
testfile = open('/root/testfile.txt','a')
testfile.write('你好')
testfile.write('世界')
testfile.close()
testfile = open('/root/testfile.txt','r')
print(testfile.readlines())
testfile.close()
[root@localhost 5]# python3 4.2.py
['helloword你好世界']
五、with语句
在实际情况中,我们应该尝试使用 with
语句处理文件对象,它会在文件用完后自动关闭,就算发生异常也没关系。它是 try-finally
块的简写:
所以上方的脚本可以简写为:
#!/usr/bin/env python3
testfile = '/root/testfile.txt'
with open(testfile,'w') as file:
file.write("hello,word"'\n')
file.write("你好,世界"'\n')
with open(testfile,'r') as file:
print(file.readlines())
with open(testfile,'a') as file:
file.write('end''\n')
with open(testfile,'r') as file:
print(file.readlines())
[root@localhost 5]# python3 5.py
['hello,word\n', '你好,世界\n']
['hello,word\n', '你好,世界\n', 'end\n']
[root@localhost 5]# cat /root/testfile.txt
hello,word
你好,世界
end
六、JSON
JSON
格式在互联网应用开发中应用非常广泛,可以作为不同的服务组件之间进行数据传递的格式。在互联网应用提供的各种 API
接口返回值基本都是 JSON
格式。
#!/usr/bin/env python3
import json
# 定义course字典
courses = {
1: 'Linux', 2: 'Git', 3: 'Vim'}
## 结构转换
# 转成json格式输出
json1 = json.dumps(courses)
print(json1)
# 转换成python字典
json2 = json.loads(json1)
print(json2)
## 文件操作
# 使用dump方法存入文件
with open('/root/course.json','w') as file:
json.dump(courses,file)
with open('/root/course.json','r') as file:
print(file.read())
# 使用load方法读取json文件
with open('/root/course.json','r') as file:
print(json.load(file))
[root@localhost 5]# python3 6.py
{
"1": "Linux", "2": "Git", "3": "Vim"}
{
'1': 'Linux', '2': 'Git', '3': 'Vim'}
{
"1": "Linux", "2": "Git", "3": "Vim"}
{
'1': 'Linux', '2': 'Git', '3': 'Vim'}
七、文件与文件夹操作
os.path
主要的用途是获取和处理文件及文件夹属性
>>> import os
>>> filename = '/root/course.json'
# 返回文件的绝对路径
>>> os.path.abspath(filename)
'/root/course.json'
#返回文件名
>>> os.path.basename(filename)
'course.json'
# 返回文件路径
>>> os.path.dirname(filename)
'/root'
# 判断路径是否为文件
>>> os.path.isfile(filename)
True
# 判断路径是否为目录
>>> os.path.isdir(filename)
False
# 判断路径是否存在
>>> os.path.exists(filename)
True