Python File and directory operations

Source: Internet
Author: User
1) Os.path
1.1 Os.path.isabs (path) is an absolute path
1.2 Os.path.isfile (PATH)
1.3 Os.path.isdir (PATH)
1.4 Os.path.islink (PATH) is a link, but returns false if the system does not support links
1.5 Os.path.ismount (path) is a drive, but unfortunately in Python 3.0 this is a function that cannot be run.
The original function is as follows:


# is a path a mount point? Either a root (with or without)
# or a UNC path with at most a/or \ after the mount point.

def ismount (path):
"" "Test whether a path is a mount point (defined as the root of drive)" "
UNC, rest = Splitunc (path)
SEPs = _get_bothseps (P)
If UNC:
Return rest in p[:0] + seps
p = splitdrive (path) [1]
Return Len (p) = = 1 and p[0] in SEPs




The error is obvious. Do not know why this function is written in the Windows platform, you can complete the function as follows
def ismount (path):
p = splitdrive (path) [1]
If Len (P) > 0:
Return (False)
Else
Return (True)


Other platforms do not have a corresponding machine and do not know the specific situation.
1.6 Os.path.abspath (path) returns an absolute path
1.7 Os.path.dirname (PATH)
1.8 Os.path.exists (PATH)
1.9 os.path.lexists (path) is the same as the EXISTS function
1.10os.path.getsize (PATH)
1.11os.path.getctime (path) returns the system time of a floating-point number on a Unix-like system that is the time of the file's most recent change,
When a file or directory is created on Windows
1.12os.path.getmtime (path) file or directory last changed time
1.13os.path.getatime (path) file or directory last accessed time
1.14os.path.samefile (path1,path2) returns true if 2 paths point to the same file or directory (not available on Windows)
1.15os.path.split (path) split path, if path is a directory, return [ParentName, DirName];
If path is a file, return [DirName, FileName]
1.16os.path.splitext (path) split path, if path is a directory, return [ParentName, '];
If path is a file, return [dirname+filename, file suffix]


2) Fileinput
Simple to use
Import file
Input for line in Fileinput.input ():
Process (line)


2.1 Fileinput.input ([files[, inplace[, Backup[,mode[,openhook]])
Create an instance of Fileinput, and if files is empty, point to the console for input, and if file is '-', turn to console for input.
By default, the file opens in text mode and needs to be specified if additional formatting is required.
2.2 Fileinput.filename () #只有当读入第一行之后, the value is assigned
2.3 Fileinput.fileno ()
2.4 Fileinput.lineno ()
2.5 Fileinput.filelineno ()
2.6 Fileinput.isfirstline ()
2.7 Fileinput.isstdin ()
2.8 Fileinput.nextfile ()
2.9 Fileinput.close ()


3) Glob
You can use simple methods to match all subdirectories or files in a directory, and the usage is simple.
3.1 Glob.glob (regression) returns a list
3.2 Glob.iglob (regression) returns a walker
This module is easy to use and highly recommended.


4) Linecache
Look at the name, you know, the cache class.
4.1 Linecache.getline (filename,lineno[, module_globals]) #获得filename的第lineno行
4.2 Linecache.clearcache ()
4.3 Linecache.checkcache ([filename]) #检查更新


5) Shutil key recommended coat, good stuff, copy and delete operations supporting file collections
5.1 Shutil.copyfileobj (FSRC, fdst[, length])
5.2 Shutil.copyfile (SRC, DST) #上面2个都是文件的复制
5.3 Shutil.copymode (SRC, DST) #除了复制内容, some other information is also copied, such as the author
5.4 Shutil.copystat (SRC, DST) #除了复制内容 and also copy access time information
5.5 shutil.copy (src, DST) #复制文件到dst when DST is a directory, copy to subdirectories
5.6 Shutil.copy2 (SRC, DST) #相当于先copy再copystat
5.7 Shutil.copytree (SRC, dst[, symlinks=false[, Ingore=none]) #复制文件夹树, note that the DST folder must not exist
5.8 Shutil.rmtree (path[, ignore_erros[, OnError])
5.9 Shutil.move (SRC,DST)

The code is as follows:


def copytree (SRC, DST, symlinks=false):
names = Os.listdir (src)
Os.makedirs (DST)
errors = []
for name in names:
SrcName = os.path.join (src, name)
DstName = Os.path.join (d St, name)
Try:
if symlinks and Os.path.islink (srcname):
Linkto = Os.readlink (srcname)
Os.symlink (Linkto, DstName)
Elif Os.path.isdir (srcname):
Copytree (SrcName, DstName, symlinks)
Else:
Copy2 (SrcName, DstName)
# XXX What's about devices, sockets etc?
Except (IOError, Os.error) as Why:
Errors.append ((SrcName, DstName, str))
# Catch the error from the RECU Rsive Copytree So, we can
# continue with other files
except Error as err:
Errors.extend (err.args[0])
Try:
Copystat (SRC, DST)
except Windowserror:
# can ' t copy file access times on Windows
Pass
except OSE Rror as Why:
Errors.extend ((SRC, DST, str))
If errors:
Raise Error (Errors)

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.