current position:Home>Common OS operations for Python

Common OS operations for Python

2022-01-30 03:42:33 Clever crane

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .

1. Get all files in the current directory

have access to os.listdir(path) function , It can return to path The specified folder contains file or Folder A list of names .

How to use it is as follows :

import os

#  Open file 
path = "D://data/"
dirs = os.listdir( path )

#  Output all files and folders 
for file in dirs:
   print (file)
 Copy code 

2. Traverse folders, including subfolders

have access to os.walk(path) function , It can traverse all the files in the directory by swimming through the directory tree .

It returns a triple (root, dirs, files) The generator ,

  • root It refers to the address of the folder being traversed
  • dirs It's a list , The contents are the names of all the directories in the folder ( Exclude subdirectories )
  • files It's a list , The content is all the files in the folder ( Exclude subdirectories )

How to use it is as follows :

import os

path = "D://data/"
for root, dirs, files in os.walk(path):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))
 Copy code 

3. Other commonly used OS operation

In addition, there are some commonly used os operation , Such as os.path.exists(path) and os.makedirs(path).

  • os.path.exists(path) Used to determine path Does the path exist , return true or false .
  • os.makedirs(path) Used to create path route .

For example, when downloading files , Hope you can Breakpoint continuation , That is, when downloading a file , First judge whether the file exists in the local path .

if not os.path.exists(path):
    #todo: download file
    downloadFile(path)
else:
    pass
 Copy code 

Sometimes when saving files , If the path does not exist, it may fail to save and report an error , So you can first judge whether the path exists , If it does not exist , First create .

if not os.path.exists(path):
    # create path
    os.makedirs(path)
    
# todo: save file
saveFiles()
 Copy code 

copyright notice
author[Clever crane],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300342310881.html

Random recommended