文件IO

文本文件:
打开文件:

1
2
3
f = open('D:/sss.txt', 'r')
print(f.read())
f.close()

用with语句打开文件:

1
2
with open('D:/sss.txt', 'r') as f:
print(f.read())

要读取非UTF-8编码的文本文件,需要给 open() 函数传入 encoding 参数
例如,读取 GBK 编码的文件:

1
2
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')
print(f.read())

二进制文件(图片视频):
读文件:

1
2
f = open('/Users/michael/test.jpg', 'rb')
print(f.read())

写文件:

1
2
with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')

StringIO和BytesIO

StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO

读取StringIO

1
2
3
4
5
6
7
8
9
10
11
from io import StringIO
f = StringIO('Hello!\nHi!\nGoodbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
输出结果:
Hello!
Hi!
Goodbye!

写文件:

1
2
3
4
5
6
7
8
9
10
11
12
from io import StringIO
f = StringIO()
print(f.write('hello'))
print(f.write(' '))
print(f.write('world!'))
print(f.getvalue())
输出:
5
1
6
hello world!

BytesIO

1
2
3
4
5
6
7
8
from io import BytesIO
f = BytesIO()
print(f.write('中文'.encode('utf-8')))
print(f.getvalue())
输出:
6
b'\xe4\xb8\xad\xe6\x96\x87'

操作文件和目录:

os模块

1
2
import os
print(os.name) #操作类型

1.获取详细的系统信息,可以调用 uname() 函数:
print(os.uname())

2.操作系统中定义的环境变量,全部保存在 os.environ 这个变量中,可以直接查看:
print(os.environ)

3.要获取某个环境变量的值,可以调用
print(os.environ.get('PATH'))

4.查看当前目录的绝对路径:
print( os.path.abspath('.'))

5.把一个路径拆分为两部分,后一部分总 是最后级别的目录或文件名:
print( os.path.split('/Users/michael/testdir/file.txt'))

6.直接得到文件扩展名
print(os.path.splitext('/path/to/file.txt'))

7.对文件重命名:
os.rename('test.txt', 'test.py')

8.删掉文件:
os.remove('test.py')

9.要列出当前目 录下的所有目录:
[x for x in os.listdir('.') if os.path.isdir(x)]

10.要列出所有的 .py 文件:
[x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']

文章目录
  1. 1. StringIO和BytesIO
    1. 1.1. 操作文件和目录: