When you read a file, you often need to traverse the folder, and Python's os.path contains many ways to manipulate files and folders. Listed below:
Os.path.abspath (Path) #返回绝对路径os. Path.basename (Path) #返回文件名os. Path.commonprefix (list) #返回多个路径中, the longest path common to all paths. Os.path.dirname (Path) #返回文件路径os. Path.exists (path) #路径存在则返回True, path corruption returned Falseos.path.lexists # Path exists returns true, path corruption also returns Trueos.path.expanduser (path) #把path中包含的 "~" and "~user" converted to user directory Os.path.expandvars (path) #根据环境变量的值替换path中包含的 "$name" and "${name}" os.path.getatime (path) #返回最后一次进入此path的时间. Os.path.getmtime (path) #返回在此path下最后一次修改的时间. Os.path.getctime (path) #返回path的大小os. Path.getsize (path) #返回文件大小, returns an error if the file does not exist Os.path.isabs (path) #判断是否为绝对路径os. Path.isfile (path) #判断路径是否为文件os. Path.isdir (path) #判断路径是否为目录os. Path.islink (path) # Determine if the path is a link os.path.ismount (path) #判断路径是否为挂载点 () os.path.join (path1[, path2[, ...]) # To synthesize a directory and file name a path os.path.normcase #转换path的大小写和斜杠os. Path.normpath (path) # Canonical path string form Os.path.realpath (path) #返回path的真实路径os. Path.relpath (path[, start]) # Calculates the relative path from start Os.path.samefile (path1, path2) #判断目录或文件是否相同os. Path.sameopenfile (FP1, FP2) #判断fp1和fp2是否指向同一文件os. Path.samestat (STAT1, STAT2) #判断stat Whether the tuple STAT1 and Stat2 point to the same file Os.path.split (path) #把路径分割成dirname和basename, returns a tuple os.path.splitdrive (path) #一般用在windows下, returns a tuple os.path.splitext (path) #分割路径 that consists of a drive name and a path, and returns a tuple of path name and file name extension os.path.splitunc (path) # Divide the path into the load point and file Os.path.walk (path, visit, Arg) #遍历path, enter each directory to invoke the Visit function, the visit function must have 3 parameters (ARG, dirname, names), DirName represents the directory name of the current directory, names represents all filenames under the current directory, and Args is the third parameter of walk Os.path.supports_unicode_filenames # Sets whether to support Unicode path names the implementation of a traversal is given below:
1 ' F:\data ' 2 # List all directories and files under a folder 3 for inch Range (0,len (list)): 4 Path = os.path.join (rootdir,list[i])5 if os.path.isfile (path): 6 # you want to manipulate the file
Python to traverse files under a folder