利用python进行文件操作在我们平常项目中也经常用到,下面是我日常工作中忽略或者没有遇到过的集中情况。
一、你想将 print() 函数的输出重定向到一个文件中去。
在 print() 函数中指定 file 关键字参数,像下面这样:
with open('d:/work/test.txt', 'wt') as f: # 这里的t是windows文件text的特有形式,会识别出换行符print('Hello World!', file=f)
注意:关于输出重定向到文件中就这些了。但是有一点要注意的就是文件必须是以文本模式打开。 如果文件是二进制模式的话,打印就会出错。
二、在读取二进制数据的时候,字节字符串和文本字符串的语义差异。
注意:在读取二进制文件中,索引和迭代动作返回的是字节的值而不是字节字符串。
>>> #Text string
>>> t = 'Hello World'
>>>t[0]'H'
>>> for c int:
...print(c)
...
H
e
l
l
o
...>>> #Byte string
>>> b = b'Hello World'
>>>b[0]72
>>> for c inb:
...print(c)
...72
101
108
108
111...>>>
如果你想从二进制模式的文件中读取或写入文本数据,必须确保要进行解码和编码操作。
with open('somefile.bin', 'rb') as f:
data= f.read(16)
text= data.decode('utf-8')
with open('somefile.bin', 'wb') as f:
text= 'Hello World'f.write(text.encode('utf-8'))
三、你想像一个文件中写入数据,但是前提必须是这个文件在文件系统上不存在。 也就是不允许覆盖已存在的文件内容。
之前思路:用os模块判断这个文件名是否存在,再做读写操作。
遗漏点:可以在 open() 函数中使用 x 模式来代替 w 模式的方法来解决这个问题。
>>> with open('somefile', 'wt') as f:
... f.write('Hello\n')
...>>> with open('somefile', 'xt') as f:
... f.write('Hello\n')
...
Traceback (most recent call last):
File"", line 1, in FileExistsEr
四、你想使用操作类文件对象的程序来操作文本或二进制字符串。
importio
s= io.StringIO() #实例化一个对象存在内存中
s.write('hello world\n') #给对象写操作
print('this is a test',file=s)
res=s.getvalue()print(res)
io.StringIO 只能用于文本。如果你要操作二进制数据,要使用 io.BytesIO 类来代替。比如:
>>> s =io.BytesIO()>>> s.write(b'binary data')>>> s.getvalue()
当你想模拟一个普通的文件的时候 StringIO 和 BytesIO 类是很有用的。 比如,在单元测试中,你可以使用 StringIO 来创建一个包含测试数据的类文件对象, 这个对象可以被传给某个参数为普通文件对象的函数。
五、你想读写一个gzip或bz2格式的压缩文件。
importgzip
with gzip.open('somefile.gz', 'rt') as f:
text=f.read()#bz2 compression
importbz2
with bz2.open('somefile.bz2', 'rt') as f:
text= f.read()
#gzip compression
importgzip
with gzip.open('somefile.gz', 'wt') as f:
f.write(text)#bz2 compression
importbz2
with bz2.open('somefile.bz2', 'wt') as f:
f.write(text)
六、总结os模块常用方法
1.os.path.dirname(path) #获得目录名
2.os.path.join(path,filename) #可以拼接目录名
3.os.path.splitext(path) #得到文件路径和格式名
4.os.path.exists('/tmp/spam') #判断文件是否存在
5.os.path.isfile(path) #判断是否是文件
6.os.path.isdir(path) #判断是否是目录
7.os.path.getsize(path) #获得文件大小
8.os.path.getmtime(path) #获得文件修改时间
9.os.listdir(path) #获得目录下所有文件
使用例子:使用 os.listdir() 函数来获取某个目录中的文件列表:
importos.path#Get all regular files
names = [name for name in os.listdir('somedir')if os.path.isfile(os.path.join('somedir', name))]#Get all dirs
dirnames = [name for name in os.listdir('somedir')if os.path.isdir(os.path.join('somedir', name))]
七、你需要在程序执行时创建一个临时文件或目录,并希望使用完之后可以自动销毁掉。
tempfile 模块中有很多的函数可以完成这任务。 为了创建一个匿名的临时文件,可以使用 tempfile.TemporaryFile :
from tempfile importTemporaryFile
with TemporaryFile('w+t') as f:#Read/write to the file
f.write('Hello World\n')
f.write('Testing\n')#Seek back to beginning and read the data
f.seek(0)
data= f.read()
TemporaryFile() 的第一个参数是文件模式,通常来讲文本模式使用 w+t ,二进制模式使用 w+b。 这个模式同时支持读和写操作,在这里是很有用的,因为当你关闭文件去改变模式的时候,文件实际上已经不存在了。 TemporaryFile() 另外还支持跟内置的 open() 函数一样的参数。
with TemporaryFile('w+t', encoding='utf-8', errors='ignore') as f: