Python Learning (ix) IO programming--folder and file operations

Source: Internet
Author: User

Python folder and file operations

We often deal with files and directories, and for these operations, Python can use the OS and Shutill modules, which contain many functions for manipulating files and directories. This way, only the methods that are commonly used are described.

The OS can manipulate simple folders and file operations, introduce the import os, use the Help (OS) or dir (OS) to see its usage. Note that some functions are in the OS module, some of which are in the Os.path module.

The Shutil module provides advanced operations for a large number of files. Specifically for file copying and deletion, the main functions are directory and file operations, as well as compression operations. Import shutil should be introduced, specific help.

But first in D:\ Create a folder Python_os under it, create a folder OS under it, and then create a test.txt under it, after which the OS example operates under that folder

      

Determine the path or file

os.path.isabs (...) # Determine if absolute path

os.path.exists (...) # to determine if there is a real

os.path.isdir (...) # Determine if it is a directory

os.path.isfile (...) # Determine if it's a file

Note: when combining two paths, do not spell the string directly, but pass the os.path.join() function so that the path delimiter for the different operating systems can be handled correctly. Under Linux/unix/mac, os.path.join() return such a string:part-1/part-2

Try

and Windows will return such a string:part-1\part-2

1 ImportOS2 ImportShutil3 4File_dir ="D:\\python_os\\os"                          #note \ \; Windows is like that; Linux and Mac are/5file_name ="Test.txt"6File_abs = Os.path.join (File_dir, file_name)#os.path.join (...) indicates a path link7 8 9 " "determine the path or file" "Ten Print(1,os.path.isabs (File_dir))#determine if absolute path One Print(2, Os.path.isabs (file_name)) A Print(3, Os.path.isabs (file_abs)) - Print(4,os.path.exists (File_abs))#Judging whether there is real - Print(5,os.path.exists (Os.path.join (File_dir,"XXX")))                 the Print(6,os.path.isdir (File_dir))#determine if it is a directory - Print(7, Os.path.isdir (file_abs)) - Print(8,os.path.isfile (File_dir))#determine if it is a file - Print(9,os.path.isfile (File_abs))

Operation Result:

Path name, file name delimited

os.path.split (...) # Separating directories and filenames/folder names

os.path.splitdrive (...) # Separator letter (Windows system)

Os.path.splitext (...) # delimited files and extensions

Operation Result:

These functions of merging and splitting paths do not require directories and files to be real, they operate only on strings.

Working directory and Creating folder operations

os.path.getcwd () # get current working directory

os.path.chdir (...) # Change Working directory

os.path.listdir (...) # List files in directory

os.path.chdir (...) # Create a single directory Note: Create multilevel with os.makedirs ()

os.path.listdir (...) # Create a multilevel directory

1 ImportOS2 3File_dir ="D:\\python_os\\os"    4 5 Print(OS.GETCWD ())#get current working directory6Os.chdir (File_dir)#change the working directory7 Print(OS.GETCWD ())8 Print(Os.listdir (File_dir))#lists all files in the current working directory Python2 does not support Os.listdir () Python3 lists all files under the current working directory9Os.mkdir ("Test_mkdir")#Create folder Test_mkdir under current working directory; Note that the same folder does not exist, or you will get an errorTenOs.makedirs ("Test_mkdir\\test1") OneOs.chdir (". \\test_mkdir")#. Represents a directory of this level ... represents a parent directory A Print(OS.GETCWD ()) -  forIinchRange (2,6):#easy to create multiple folders with a For loop, etc. -Dir_name ="Test"+Str (i) theOs.mkdir (Dir_name)

After executing the above instance code, a new empty Test_mkdir folder is created in the OS folder, and an empty folder Test1 to Test5 is created under the Test_dir folder.

Creating a folder can be an error because: (1) A path already exists (either a file or a folder) (2) The drive does not exist (3) the disk is full (4) the disk is read-only or has no write permission

Delete Folder/File

os.rmdir (...) # Delete Empty folder Note: Must be an empty folder if you want to delete the folder and all files under it, you need to Shutil

os.remove (...) # Delete a single file

shutil.rmtree (...) # Delete folder and all files under it

On the above example folder basis, the operation deletes the Test1 folder (empty folder available Os.rmdir ()), deletes test_mkdir and all its files (); The sample code is as follows

1 ImportOS2 ImportShutil3 4File_dir ="D:\\python_os\\os"                    5 6 " "Delete files/folders" "7Os.chdir (file_dir+"\\test_mkdir")                    8 Print(OS.GETCWD ())#ensure that the current working directory9 Print(Os.listdir (OS.GETCWD ()))#View all files under the current folderTenOs.rmdir ("test1")#Delete test1 folder (empty folder) One Print(Os.listdir (OS.GETCWD ())) AOs.chdir (".. \\") - Print(OS.GETCWD ())#switch to parent directory - Print(Os.listdir (OS.GETCWD ())) theShutil.rmtree ("Test_mkdir")#Delete Test_mkdir and all files under it

The results are as follows: (1) path does not exist (2) path subdirectory has files or sub-directories (Os.rmdir) (3) No Operation permissions or read-only

        

Just delete a single file, then use os.remove ("test.txt") , the possible cause of the exception: (1) The file does not exist (2) There is no operation permission on the file or read-only.

Renaming

You can rename a file or folder Os.rename (Oldfilename, NewFileName)

Create a new folder in the OS folder test, file Test.txt

1 " "Renaming folders/Files" "2 Os.chdir (File_dir)3 Print(Os.listdir (OS.GETCWD ()))4Os.rename ("Test","test1")    5Os.rename ("Test.txt","Test1.txt")#Rename , note the need to have an extension6 Print(Os.listdir (OS.GETCWD ()))

The resulting results are as follows: (1) oldfilename old file name does not exist (file with extension) (2) NewFileName new file already exists

    

Note: The extension of the new file cannot be omitted, and it is theoretically necessary to keep the type consistent, but this is also a way to change the file type (equivalent to directly changing the file extension)

    

Python Learning (ix) IO programming--folder and file operations

Related Article

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.