Here, we will introduce how to use the os module and pathlib module as a file scanning method using Python.
The os module is a basic module for handling files and directories. The methods that are often used are as follows.
import os
directory = 'Directory name'
file = 'file name'
file_path = os.path.join(directory, file)
print(file_path) #Directory name/file name
print(os.path.isfile(file_path)) # True
print(os.path.isdir(file_path)) # False
print(os.path.isdir(directory)) # True
print(os.path.exists(file_path)) # True
entry_list = []
for entry in os.listdir(directory):
entry_list.append(entry)
print(directory_list)
directory_list = []
file_list = []
path_list = []
for root, dirs, files in os.walk(directory):
for drc in dirs:
directory_list.append(drc)
for file in files:
file_list.append(file)
file_path.append(os.path.join(root, file))
print(directory_list)
print(file_list)
print(path_list)
Since Python 3.4, you can use the pathlib module.
from pathlib import Path
p_dir = Path('Directory name')
p_file = Path('file name')
p_path = p_dir / p_file
p_path.mkdir(parents=True, exist_ok=True)
print(p_path)
print(p_path.parts)
print(p_path.parent)
print(p_path.name)
print(p_path.stem)
print(p_path.suffix)
print(p_path.is_file()) # True
print(p_path.is_dir()) # False
print(p_dir.is_dir()) # True
print(p_path.exists()) # True
p_path.rmdir()
print(p_path.exists()) # False
Here, I explained about the os module and the pathlib module. There is still a lack of explanation, so I will add it later.
What is the programming language Python? Can it be used for AI and machine learning?
Recommended Posts