Python folder and file operation implementation code

  • 2020-04-02 13:50:17
  • OfStack

Folder and file search, delete and other functions in the OS module. When using, we need to import this module.

The import method is:

The import of OS

Get the current directory

S = OS. Getcwd ()

The current directory (that is, the folder) is stored in # s
For example, if you run abc.py, typing this command will return the location of the ABC folder.
For A simple example, we put abc.py into A folder. And you want to generate A new folder in A folder no matter where you put the A folder on your hard drive. And the folder name is automatically generated according to time.


import os
import time
folder = time.strftime(r"%Y-%m-%d_%H-%M-%S",time.localtime())
os.makedirs(r'%s/%s'%(os.getcwd(),folder))

Change the current directory

OS. The chdir (" C: \ \ 123 ")
Set the current directory to "C:\123", equivalent to the DOC command CD C:\123    
Throws an exception when the specified directory does not exist.
Exception type: WindowsError
Linux did not try, I do not know which
 
Split a path name into two parts: the directory name and the file name
Fpath, fname = os.path.split(" the path you want to split ")
Such as:
A, b = os.path. Split ("c:\\123\\456\\test.txt")
Print a
Print b
Display:
C: \ 123\456
Test the. TXT
 
four     Decompose the extension of the file name

Fpathandname, fext = os.path.splitext
Such as:
A, b = OS. Path. Splitext (" c: \ \ 123 \ \ 456 \ \ test TXT ")
Print a
Print b
Display:
C: \ \ 456\123 test
.txt
 
Determine whether a path (directory or file) exists

B = os.path. Exists (" the path you want to determine ")
Returns the value b: True or False
 
Determine whether a path is a file
B = os.path. Isfile (" the path you want to judge ")
Returns the value b: True or False
 
Determine whether a path is a directory
B = os.path. Isdir (" the path you want to determine ")
Returns the value b: True or False
 
Get a list of files and subdirectories in a directory              
L = os.listdir(" the path you want to determine ")
Such as:
L = os.listdir("c:/")
Print the L
Display:
[' 1. Avi ', '1. JPG', '1. TXT', 'CONFIG. SYS', 'Inetpub', 'IO. SYS', 'KCBJGDJC', 'KCBJGDYB', 'KF_GSSY_JC', 'MSDOS. SYS', 'MSOCache', 'NTDETECT.COM', 'NTLDR', 'pagefile. SYS', 'PDOXUSRS.NET', 'Program Files', 'Python24', 'Python31', 'QQVideo. Cache', 'RECYCLER', 'System Volume Information' and 'TDDOWNLOAD', 'test. TXT', 'WINDOWS']
There are both files and subdirectories
Gets a list of all subdirectories in a specified directory


def getDirList( p ):
    p = str( p )
    if p=="":
       return [ ]
    p = p.replace( "/","\")
    if p[ -1] != "\":
       p = p+"\"
    a = os.listdir( p )
    b = [ x  for x in a if os.path.isdir( p + x ) ]
    return b
print  getDirList( "C:\" )

Results:
[' Documents and Settings' and 'Downloads',' HTdzh ', 'KCBJGDJC', 'KCBJGDYB', 'KF_GSSY_JC', 'MSOCache', 'Program Files',' Python24 ', 'Python31', 'QQVideo. Cache', 'RECYCLER', 'System Volume Information', 'TDDOWNLOAD', 'WINDOWS']

Gets a list of all files in a specified directory


def getFileList( p ):
    p = str( p )
    if p=="":
       return [ ]
    p = p.replace( "/","\")
    if p[ -1] != "\":
       p = p+"\"
    a = os.listdir( p )
    b = [ x  for x in a if os.path.isfile( p + x ) ]
    return b
print  getFileList( "C:\" )

Results:
[' 1. Avi ', '1. JPG', '1. TXT', '123. TXT', '12345. TXT', '2. Avi', 'Amy polumbo y', 'AUTOEXEC. BAT', 'boot. Ini', 'bootfont. Bin', 'CONFIG. SYS', 'IO. SYS', 'MSDOS. SYS', 'NTDETECT.COM', 'NTLDR', 'pagefile. SYS, 'PDOXUSRS.NET', 'test. TXT']
 
Create subdirectories

OS. Makedirs (     The path)     # path is "subdirectory to create"
Such as:
OS. Makedirs (     "C: \ \ 123 \ \ 456 \ \ 789")
The invocation may fail for the following reasons:
(1) when the path already exists (whether it is a file or a folder)
(2) drive does not exist
(3) the disk is full
(4) the disk is read-only or has no write permissions

Delete subdirectories

OS. Rmdir (path)     # path: "subdirectories to delete"
Possible causes of the anomaly:
(1) path does not exist
(2) there are files or subdirectories in the path subdirectory
(3) no operation permission or read-only
When testing this function, create the subdirectory yourself.

Delete files

OS. Remove (     Filename)     # filename: "the name of the file to be deleted"
Possible causes of the anomaly:
(1)     The filename does not exist
(2) no operation permissions or read-only for filename files.

File name change

OS. The name (oldfileName newFilename)
Causes of anomalies:
(1) oldfilename does not exist
(2) when a newFilename file already exists, you need to delete the newFilename file first.


Related articles: