通过文件名查找文件-python cookbook(第3版)高清中文完整版

时间:2024-06-29 23:06:47
【文件属性】:

文件名称:通过文件名查找文件-python cookbook(第3版)高清中文完整版

文件大小:4.84MB

文件格式:PDF

更新时间:2024-06-29 23:06:47

python cookbook 第3版 高清 中文完整版

13.9 通过文件名查找文件 问题 You need to write a script that involves finding files, like a file renaming script or a log archiver utility, but you’d rather not have to call shell utilities from within your Python script, or you want to provide specialized behavior not easily available by “shelling out.” 解决方案 To search for files, use the os.walk() function, supplying it with the top-level directory. Here is an example of a function that finds a specific filename and prints out the full path of all matches: #!/usr/bin/env python3.3 import os def findfile(start, name): for relpath, dirs, files in os.walk(start): if name in files: full_path = os.path.join(start, relpath, name) print(os.path.normpath(os.path.abspath(full_path))) if __name__ == ‘__main__’: findfile(sys.argv[1], sys.argv[2]) Save this script as findfile.py and run it from the command line, feeding in the starting point and the name as positional arguments, like this: bash % ./findfile.py . myfile.txt 讨论 The os.walk() method traverses the directory hierarchy for us, and for each directory it enters, it returns a 3-tuple, containing the relative path to the directory it’s inspecting, a list containing all of the directory names in that directory, and a list of filenames in that directory. For each tuple, you simply check if the target filename is in the files list. If it is, os.path.join() is used to put together a path. To avoid the possibility of weird looking paths


网友评论