Python Operations files and directories
Read and write files are relatively simple, a little special attention is good.
The file opened by default in Python is GBK decoded, and our file is UTF-8 encoded, so if the text contains Chinese, there will be an exception or garbled. The manually added encoding='utf-8' representation is opened in Utf-8 mode at this time.
Of course, when Python is written, it is also written by default in GBK encoding. And the file is usually saved in the utf-8 format, so if you do not specify the encoding to write, the Chinese is garbled.
With open (' Abc.txt ', encoding= ' Utf-8 ') as F:print (F.read ()) # This opens the file in Chinese and is not afraid # of course when Python is written, the default is written in GBK encoding. And the file is saved in utf-8 format, so do not specify the encoding of the Write, a written in Chinese is garbled with open (' Abc.txt ', ' W ', encoding= ' utf-8 ') as F: f.write (' Hello ')
Okay, get to the chase.
OS Module
Current working directory
The following code can get/toggle the current working directory, that is, . the path represented by
Import Osprint (OS.GETCWD ()) # F:\PythonProjectos.chdir (R ' D:\python ') print (OS.GETCWD ()) # D:\pythonprint ( Os.path.abspath ('. ')) # d:\python# because the working directory switches to D:\python, the aa.txt is generated under it with open (' Aa.txt ', ' W ', encoding= ' utf-8 ') as F: f.write (' Hello ')
os.chdirYou can switch the current working directory, that is, change the directory you are . pointing to. The relative path aa.txt is then generated under the switched path. These two paths express the same meaning
There are also two points, which represent the parent directory of the current directory. That's ..\aa.txt what it D:\aa.txt means.
Absolute path and relative path
Print (Os.path.abspath (' Aa.txt ')) # D:\python\aa.txtprint (os.path.isabs (' Aa.txt ')) # Falseprint ( Os.path.isabs ('. ')) #False
The above code, the first function returns the absolute path of the parameter path, and the second function checks whether a path is a relative path.
Gets the path before and after the last Slash.
# get the last slash behind the section print (Os.path.basename (R ' D:\python\aa.txt ')) # Aa.txtprint (Os.path.dirname (R ' D:\python\aa.txt ')) # D : \python# Of course Use the following function to obtain both print (Os.path.split (R ' D:\python\aa.txt ')) # (' D:\\python ', ' aa.txt ')
Split in other ways
Print (Os.path.splitext (R ' D:\python\aa.txt ')) # (' D:\\python\\aa ', '. txt ') print (os.path.splitdrive (R ' D:\python\ Aa.txt ') # (' D: ', ' \\python\\aa.txt ')
os.path.splitextThis function makes it easy to get the file suffix name, and returns null if the provided path is a folder.
os.path.splitdriveDelimited as a drive letter.
Note that they all return tuples .
Check the path
Check that a path does not exist, is it a file? or a folder?
Print (Os.path.isfile (' D:\python ')) # Falseprint (Os.path.isdir (' D:\python ')) # Trueprint (os.path.exists (' D:\ Python ')) # True
Create a folder
Os.mkdir (' D:\good ') # True can only establish a non-existent directory, if there will be an error os.mkdir (' D:\good\job ') # True comment off the last sentence, because D:\good already exists, This is equivalent to or just a new level of non-existent directory Os.mkdir (R ' D:\aa\bb ') # Error!! Because both the AA and BB folders do not exist, the D:\AA path cannot be found, so you cannot create Os.makedirs (R ' D:\aa\bb ') # This function does not have the upper limit, the tube does not exist peremptorily created, anyway, it will eventually generate this path. But if this path already exists, it will be an error.
As you can see os.makedirs , it is more common to create all the folders in the path. os.mkdirYou must also ensure that the parent directory exists, so you can only create a new level directory.
Connection path
Print (Os.path.join (R ' D:\python ', ' Aa.txt ')) # D:\python\aa.txt
This function is also commonly used to connect two paths and combine them into a new path to return.
Traverse Folder
# returns the tuple, which is the current folder path, the subfolder under the current path, the file for Current_path under the current path, subfolders, Filesname in Os.walk (R ' D:\Cleaner '):p rint (f ' { Current_path}\n{subfolders}\n{filesname} ') print ('-' *30)
os.walkYou can recursively traverse all the files and folders in a given path. Look at what this function will print in this directory. This function returns a tuple, which is (the current path, all folders under that path, all the files under that path), and then continually recursively deep, returning such tuples. So the For loop above executes several times until the path is deepest.
d:\cleaner[' CCleaner ' [' Desktop.ini ']------------------------------d:\cleaner\ccleaner[' Lang ' [' Branding.dll ', ' Business.dat ', ' CCleaner.dat ', ' CCleaner.exe ', ' Ccleaner.ini ', ' CCleaner64.exe ', ' Portable.dat ']------------------ ------------....
Delete files/folders
# permanently delete, do not enter Recycle Bin Os.remove (R ' D:\aaaa.txt ') # Same as Os.unlink () # directory is empty to delete, just delete current folder Os.rmdir (R ' D:\aaa\bbb\ccc\eee ') # This method also cannot delete the non-empty directory, but deleted the empty folder sub-EEE, if found that the parent text folders are also empty delete os.removedirs (R ' D:\aaa\bbb\ccc\eee ') # The remaining d:\aaa\bbb# strong, the directory of all Files /folder is all deleted, regardless of the content is empty. Use Shutil.rmtree (R ' D:\aaa ') with caution
Renaming
# To rename a folder, you must ensure that the original path exists, the destination path cannot already exist Os.rename (R ' D:\python ', ' D:\good ') # Rename the file, you must ensure that the original path exists, the destination path cannot already exist Os.rename (R ' D:\good\ Aa.txt ', R ' D:\good\bb.txt ') # above can not be used in the case of the target address exists, this function is rude, if the target path already exists, it will overwrite, with caution with Os.replace (R ' D:\good\bb.txt ', R ' D:\good\ Cc.txt ')
Get the size of a file
Gets the size of the file, in bytes
Print (Os.path.getsize (R ' D:\good\cc.txt '))
Shutil Module
The OS module is quite powerful, but there are some features such as copy/Cut files and folders exist with the Shutil module.
Just look at the code.
Copy
# if the movie directory exists, the file is copied to the directory. Des1 = shutil.copy (R ' D:\findall.txt ', R ' E:\Movie ') # If there is no such directory, then new mov file, no suffix des2= shutil.copy (r ' D:\findall.txt ', R ' e:\ Mov ') # Of course Specify the suffix name, copy the source file and rename des2= shutil.copy (R ' D:\findall.txt ', R ' E:\Mov.txt ') # Copy only copy last access time Des3 = Shutil.copy ( R ' D:\findall.txt ', R ' E:\findit.txt ') # copy2 copy all metadata at the same time including the modified time and last access time Des4 = Shutil.copy2 (R ' D:\findall.txt ', R ' e:\ Find.txt ') # no copy of access time and modified time DES5 = Shutil.copyfile (R ' D:\findall.txt ', R ' E:\findaa.txt ') # you can see the path that is returned is the new file where print (f ' {des1} \N{DES2}\N{DES3} ') # Copy the entire folder (all contents inside) to another folder, which cannot be a folder that already exists Shutil.copytree (R ' D:\abc ', R ' E:\Movie ')
Move
# cut the file, ABC does not exist to move the file and renamed to ABC, the ABC directory exists then put in the directory Shutil.move (R ' D:\findall.txt ', R ' E:\abc ') # Destination address if the file, then move and rename Shutil.move ( R ' D:\findall.txt ', R ' E:\aa.txt ') # Cut folder, if the target directory already exists, then cut and put into that directory, if the target directory does not exist, it is equivalent to moving the directory to the destination address and renaming the folder Shutil.move (R ' D:\abc ' , R ' E:\avb ')
OK, the operation of files and directories is also often used in daily life. Learning these things can be done automatically.
by @sunhaiyu
2017.6.26