How to use the ls function in Python?
In Python, “ls” is a command in Unix and Linux systems used to list files and folders in a specified directory. There is no built-in “ls” function in Python, but the os module can be used to perform similar operations.
To list the files and folders in the current directory, you can use the os.listdir() function.
import os
files = os.listdir()
for file in files:
print(file)
You can pass the directory path as a parameter to the os.listdir() function to list the files and folders in a specified directory.
import os
path = '/path/to/directory'
files = os.listdir(path)
for file in files:
print(file)
You can use the functions from the os.path module to specify whether you want to only list files or only list folders.
import os
path = '/path/to/directory'
files = os.listdir(path)
for file in files:
if os.path.isfile(os.path.join(path, file)): # 只列出文件
print(file)
if os.path.isdir(os.path.join(path, file)): # 只列出文件夹
print(file)
This way, you can simulate the use of the ls function in Python.