Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Python os and os.path modules

Shulou Source: shulou.com Published: 2022-06-01 01:47:06 09月21日 Update

In this article, the editor introduces in detail "how to use Python os and os.path modules". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use Python os and os.path modules" can help you solve your doubts.

1. Purpose: to achieve reading only files with the extension xlsx in Python

Solution:

Use the os module.

The solution is as follows:

1. Determine the directory

2. Loop through each file

3. Filter files that meet the conditions and read data

The specific code is as follows:

Import os# 1. First define the path filepath = 'E:/old/ work / database table' # 2, loop through each file under the path for filename in os.listdir (filepath): # 3, list the files in the file ending with .xlsx if filename.endswith (('.xlsx')): print (filename)

The results are as follows:

2. Purpose: to use Python to traverse the files in each folder under the specified directory

Solution:

Using the join method of the os.path module

The solution is as follows:

1. Define a function and use this function to iterate through it to specify all subfolders under the directory

2. Call the function to view all the files

Specific code:

Def get_filelist (dir,Filelist): if os.path.isfile (dir): # determine whether path is a file Filelist.append (dir) # add a path to the list elif os.path.isdir (dir): # determine whether the path is a directory for s in os.listdir (dir): # traverse every file in the directory new_dir = os.path.join (dir S) get_filelist (new_dir,Filelist) # call the defined function return Filelist list_ = get_filelist ('E:/old/ work / database table', []) print (len (list_)) for l in list_: print (l)

The results are as follows:

After reading this, the article "how to use Python os and os.path modules" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Tags: Files modules directories functions paths ideas data articles methods loops code content databases folders purposes results work appropriateness new knowledge more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Apple Docker macOS OPPO Reno