Python/文件
外观
< Python
文件I/O
[编辑]读整个文件:
inputFileText = open("testit.txt", "r").read() print(inputFileText) 参数值"r"表示文件只读模式打开。
从文件中读入指定数量的字节:
inputFileText = open("testit.txt", "r").read(123) print(inputFileText) 打开文件后,用seek()重定位文件当前位置,用tell()获取文件当前位置。如下例:
>>> f=open("/proc/cpuinfo","r") >>> f.tell() 0L >>> f.read(10) 'processor\t' >>> f.read(10) ': 0\nvendor' >>> f.tell() 20L >>> f.seek(10) >>> f.tell() 10L >>> f.read(10) ': 0\nvendor' >>> f.close() >>> f <closed file '/proc/cpuinfo', mode 'r' at 0xb7d79770> close()函数用于关闭一个打开的文件。
一次读一行:
for line in open("testit.txt", "r"): print(line) readlines()函数将返回文件的所有行,作为字符串组成的列表。每个字符串以换行符结尾。
readline()函数读取当前行,作为字符串返回。字符串以换行符结尾。
写文件时,需要在open()用参数"w":
outputFileText = "Here's some text to save in a file" open("testit.txt", "w").write(outputFileText) 追加文件时,需要在open()用参数"a":
outputFileText = "Here's some text to add to the existing file." open("testit.txt", "a").write(outputFileText) 从Python 2.5开始,可以用关键字with保证文件句柄被释放、异常安全:
with open("input.txt") as file1: data = file1.read() # process the data 或者:
with open("input.txt") as file1: for line in file1: print(line) 关于关键字with,参见Context Managers。
外部链接:
- 7.5. The with statement, python.org
- PEP 343 -- The "with" Statement, python.org
对文件的相关测试
[编辑]确定路径是否存在:
import os os.path.exists('<path string>') 对于Microsoft Windows™,可写为:
import os os.path.exists('C:\\windows\\example\\path') 或写成"raw"字符串(r):
import os os.path.exists(r'C:\windows\example\path') os.path还包括一些有用函数:
>>> import os >>> os.path.isfile("/") False >>> os.path.isfile("/proc/cpuinfo") True >>> os.path.isdir("/") True >>> os.path.isdir("/proc/cpuinfo") False >>> os.path.ismount("/") True >>> os.path.islink("/") False >>> os.path.islink("/vmlinuz") True >>> os.path.realpath("/vmlinuz") '/boot/vmlinuz-2.6.24-21-generic' 文件常见操作
[编辑]copy或move文件,使用库shutil
import shutil shutil.move("originallocation.txt","newlocation.txt") shutil.copy("original.txt","copy.txt") 对一个目录的递归复制用copytree(),对一个目录的递归move用rmtree():
import shutil shutil.copytree("dir1","dir2") shutil.rmtree("dir1") 删除一个文件,使用os库中的remove()函数:
import os os.remove("file.txt") 查找文件
[编辑]可以用glob查找文件:
glob.glob('*.txt') # Finds files in the currect directory ending in dot txt glob.glob('*\\*.txt') # Finds files in any of the direct subdirectories # of the currect directory ending in dot txt glob.glob('C:\\Windows\\*.exe') for fileName in glob.glob('C:\\Windows\\*.exe'): print(fileName) glob.glob('C:\\Windows\\**\\*.exe', recursive=True) # Py 3.5: ** allows recursive nesting glob通配符:
| 通配符 | 功能 |
|---|---|
| * | 匹配0或多个字符 |
| ** | 匹配所有文件、目录、子目录和子目录里的文件(3.5版本新增) |
| ? | 匹配1个字符,与正则表达式里的?不同 |
| [exp] | 匹配指定范围内的字符,如:[1-9]匹配1至9范围内的字符 |
| [!exp] | 匹配不在指定范围内的字符 |
目录的内容可以用listdir函数列出:
filesAndDirectories=os.listdir('.') for item in filesAndDirectories: if os.path.isfile(item) and item.endswith('.txt'): print "Text file: " + item if os.path.isdir(item): print "Directory: " + item 得到一个目录下所有项目,包括在子目录下的:
for root, directories, files in os.walk('/user/Joe Hoe'): print "Root: " + root # e.g. /user/Joe Hoe/Docs for dir1 in directories: print "Dir.: " + dir1 # e.g. Fin print "Dir. 2: " + os.path.join(root, dir1) # e.g. /user/Joe Hoe/Docs/Fin for file1 in files: print "File: " + file1 # e.g. MyFile.txt print "File 2: " + os.path.join(root, file1) # e.g. /user/Joe Hoe/Docs/MyFile.txt 得到一个目录下的所有.txt,包括子目录,使用list comprehension:
files = [os.path.join(r, f) for r, d, fs in os.walk(".") for f in fs if f.endswith(".txt")] # As iterator files = (os.path.join(r, f) for r, d, fs in os.walk(".") for f in fs if f.endswith(".txt")) 外部链接:
- glob, python.org
- glob, Py 3, python.org
- os.listdir, python.org
- os.walk, python.org
- os.path.join, python.org
当前目录
[编辑]得到当前工作目录:
os.getcwd() 改变当前工作目录:
os.chdir('C:\\') 外部链接
[编辑]- os — Miscellaneous operating system interfaces in Python documentation
- glob — Unix style pathname pattern expansion in Python documentation
- shutil — High-level file operations in Python documentation
- Brief Tour of the Standard Library in The Python Tutorial