1. 文本数据的读写
- open() & write() : rt模式的刷新模式
当我们需要读写各种不同编码的文本数据(如ASCII,UTF-8或UTF-16编码等), 可以直接使用带rt模式的open()内置函数。如果需要将文本内容写入到一个文件中,就要使用带有 wt 模式的 write() 函数。如果文件不存在,系统就会新建一个文件;如果先前文件中存在内容,那么也会被强制刷新。
# 将整个文档作为字符串读进来
with open('test.txt', 'rt') as f:
data = f.read()
#迭代模式 按行读取文档内容
with open('test.txt', 'rt') as f:
for line in f:
print(line)
text = 'why do you want to go abroad?'
with open('test_w.txt', 'wt') as f:
f.write(text)
- open() + at模式:已存在文件添加内容
文件的读写操作默认使用系统编码,可以通过调用 sys.getdefaultencoding() 来得到。 在大多数机器上面都是utf-8编码。如果你已经知道你要读写的文本是其他编码方式, 那么可以通过传递一个可选的 encoding 参数给open()函数。
Note:
1.使用with语句是为了给文件创建了一个上下文环境, 但 with 控制块结束时,文件会自动关闭。也可以不使用 with 语句,但是这时候你就必须记得手动关闭文件,f.close()。
2.关于换行符的识别问题,在Unix和Windows中是不一样的(分别是 \n 和 \r\n)。 默认情况下,Python会以统一模式处理换行符。 这种模式下,在读取文本的时候,Python可以识别所有的普通换行符并将其转换为单个 \n 字符。
2. 打印输出到文件中
在 print() 函数中指定 file 关键字参数,可以将待写入文档的内容重定向到该文档中。
- print() & paras: file
with open('test_w.txt', 'wt') as f:
print('My dream!', file = f)
Note: 文件必须是以文本模式打开。 如果文件是二进制模式的话,打印就会出错。
3. 使用其他分隔符或行终止符打印
很多时候,我们在用print() 函数输出数据时,希望改变间隔符或者行终止符。这时候可以使用在 print() 函数中使用 sep 和 end 关键字参数。
# default
print('ziheng', 22, 3.14)
# >>> ziheng 22 3.14
print('ziheng', 22, 3.14, sep = ',')
# >>> ziheng,22,3.14
print('ziheng', 22, 3.14, sep = ',', end = '??\n')
# >>> ziheng,22,3.14??
# 使用end参数 还可以让输出禁止换行
for num in range(5):
print(num)
for num in range(5):
print(num, end = ',')
# >>> 0,1,2,3,4,
4. 文件路径名操作
如何通过文件路径名获得文件名、目录名以及绝对路径?
- os.path
import os
path = 'D:\\用户目录\\我的文档\\pythonPro\\test.txt'
print(os.path.basename(path))
# >>> test.txt
print(os.path.dirname(path))
# >>> D:/用户目录/我的文档/pythonPro
# 提供新的文件目录
print( os.path.join(os.path.dirname(path), 'newFile',os.path.basename(path)))
# >>> D:\用户目录\我的文档\pythonPro\newFile\test.txt
# 文件后缀名
print(os.path.splitext(path))
# >>> ('D:\\用户目录\\我的文档\\pythonPro\\test', '.txt')
对于任何的文件名的操作,都使用 os.path 模块。 特别是为了可移植性考虑, 因为 os.path 模块知道Unix和Windows系统之间的差异并且能够可靠地处理类似 Data/data.csv 和 Data\data.csv 这样的文件名。
5. 文件的存在性
在应用程序中,特别是读写文件之前,我们应该判断文件是否存在。
- os.path.exists
import os
print( os.path.exists('test.txt'))
# >>> True
print( os.path.isfile('test.txt'))
# >>> True
print( os.path.exists('D:\\用户目录'))
# >>> True
print( os.path.isdir('D:\\用户目录'))
# >>> True
使用 os.path 来进行文件测试是很简单的。唯一需要注意的就是你需要考虑文件权限的问题,特别是在获取元数据时候(这里说的元数据指的是:文件大小getsize / 文件时间getmtime)。
6. 获取文件列表
获取文件系统中某个文件目录下所有的文件。结果会返回目录中所有文件列表,包括所有文件,子目录,符号链接等等。 如果需要通过某种方式过滤数据,可以结合 os.path 库中的一些函数来使用列表推导。
- os.listdir
import os
name = 'D:\\用户目录\\我的文档'
print( os.listdir(name) )
# >>> ['desktop.ini', 'pythonPro', 'Tencent Files', 'test1.txt']
# 文件过滤 -> 得到所有文件
files = [num for num in os.listdir(name)
if os.path.isfile(os.path.join(name, num))]
print( files )
# >>> ['desktop.ini', 'test1.txt']
# 文件过滤 -> 得到所有文件夹
filefold = [num for num in os.listdir(name)
if os.path.isdir(os.path.join(name, num))]
print( filefold )
# >>> ['pythonPro', 'Tencent Files']
# 文件过滤 -> 获取特定类型文件
txtfiles = [num for num in os.listdir(name)
if num.endswith('.txt')]
print(txtfiles)
# >>> ['test1.txt']
获取目录中的列表很容易,但是其返回结果只是目录中实体名列表而已。 如果还想获取其他的元信息,比如文件大小,修改时间等等, 还需要使用到 os.path 模块中的函数或着 os.stat() 函数来收集数据。
文章参考《Python3-cookbook》