本节内容:
pythonbiaozhunku/ target=_blank class=infotextkey>python标准库实例教程,学习下python模块fileinput、shutil、os、tempfile等的用法。
fileinput 模块允许你循环一个或多个文本文件的内容
使用 fileinput 模块循环一个文本文件
例子:
复制代码 代码示例:
import fileinput
import sys
for line in fileinput.input("samples/sample.txt"):
sys.stdout.write("-> ")
sys.stdout.write(line)
-> We will perhaps eventually be writing only small
-> modules which are identified by name as they are
-> u
sed to build larger ones, so that devices like
-> indentation, rather than delimiters, might become
-> feasible for expressing local structure in the
-> source language.
-> -- Donald E. Knuth, December 1974
也可以使用 fileinput 模块获得当前行的元信息 (meta information). 其中包括 isfirstline , filename , lineno
使用 fileinput 模块处理多个文本文件
复制代码 代码示例:
import fileinput
import glob
import string, sys
for line in fileinput.input(glob.glob("samples/*.txt")):
if fileinput.isfirstline(): # first in a file?
sys.stderr.write("-- reading %s --n" % fileinput.filename())
sys.stdout.write(str(fileinput.lineno()) + " " + string.upper(line))
-- reading samplessample.txt --
1 WE WILL PERHAPS EVENTUALLY BE WRITING ONLY SMALL
2 MODULES WHICH ARE IDENTIFIED BY NAME AS THEY ARE
3 USED TO BUILD LARGER ONES, SO THAT DEVICES LIKE
4 INDENTATION, RATHER THAN DELIMITERS, MIGHT BECOME
5 FEASIBLE FOR EXPRESSING LOCAL STRUCTURE IN THE
6 SOURCE LANGUAGE.
7 -- DONALD E. KNUTH, DECEMBER 1974
文本文件的替换操作很简单。
只需要把 inplace 关键字参数设置为 1,传递给 input 函数,该模块会帮你做好一切。
使用 fileinput 模块将 CRLF 改为 LF
复制代码 代码示例:
import fileinput, sys
for line in fileinput.input(inplace=1):
# convert Windows/DOS text files to Unix files
if line[-2:] == "rn":
line = line[:-2] + "n"
sys.stdout.write(line)
shutil 实用模块包含了一些用于复制文件和文件夹的函数.
使用 shutil 复制文件
复制代码 代码示例:
import shutil
import os
for file in os.listdir("."):
if os.path.splitext(file)[1] == ".py":
print file
shutil.copy(file, os.path.join("backup", file))
aifc-example-1.py
anydbm-example-1.py
array-example-1.py
...
copytree 函数用于复制整个目录树 (与 cp -r 相同), 而 rmtree 函数用于删除整个目录树 (与 rm -r )
使用 shutil 模块复制/删除目录树
复制代码 代码示例:
import shutil
import os
SOURCE = "samples"
BACKUP = "samples-bak"
# create a backup directory
shutil.copytree(SOURCE, BACKUP)
print os.listdir(BACKUP)
# remove it
shutil.rmtree(BACKUP)
print os.listdir(BACKUP)
['sample.wav', 'sample.jpg', 'sample.au', 'sample.msg', 'sample.tgz',
...
Traceback (most recent call last):
File "shutil-example-2.py", line 17, in ?
print os.listdir(BACKUP)
os.error: No such file or directory
tempfile 模块允许你快速地创建名称唯一的临时文件供使用.
使用 tempfile 模块创建临时文件
复制代码 代码示例:
import tempfile
import os
tempfile = tempfile.mktemp()
print "tempfile", "=>", tempfile
file = open(tempfile, "w+b")
file.write("*" * 1000)
file.seek(0)
print len(file.read()), "bytes"
file.close()
try:
# must remove file when done
os.remove(tempfile)
except OSError:
pass
tempfile => C:TEMP~160-1
1000 bytes
TemporaryFile 函数会自动挑选合适的文件名, 并打开文件而且它会确保该文件在关闭的时候会被删除. (在 Unix 下, 你可以删除一个已打开的文件, 这 时文件关闭时它会被自动删除. 在其他平台上, 这通过一个特殊的封装类实现.)
使用 tempfile 模块打开临时文件
复制代码 代码示例:
import tempfile
file = tempfile.TemporaryFile()
for i in range(100):
file.write("*" * 100)
file.close() # removes the file!