你应该知道的 10 个Python文件系统方法
在使用任何语言进行编程时,程序与操作系统(Windows、Linux、macOS)之间的交互在任何开发人员的生活中都会变得很重要。这种交互可能包括将文件从一个位置移动到另一个位置、创建新文件、删除文件等。
在本文中,我们将讨论 OS 的 10 个基本文件系统方法和Python中的 Shutil 模块,它们有助于与我们的操作系统交互并使用依赖于操作系统的功能。
os.getcwd()
os.getcwd() 方法告诉我们当前工作目录(CWD)的位置。
例子:
Python3
# Python program to explain os.getcwd() method
# importing os module
import os
# Get the current working
# directory (CWD)
cwd = os.getcwd()
# Print the current working
# directory (CWD)
print("Current working directory:", cwd)
Python3
# Python3 program to change the
# directory of file using os.chdir() method
# import os library
import os
# change the current directory
# to specified directory
os.chdir(r"C:\Users\Gfg\Desktop\geeks")
print("Directory changed")
Python3
# Python program to explain os.listdir() method
# importing os module
import os
# Get the path of current working directory
path = '/home'
# Get the list of all files and directories
# in current working directory
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
print(dir_list)
Python3
# Driver function
import os
for (root,dirs,files) in os.walk('/home/nikhil/Desktop/', topdown=True):
print (root)
print (dirs)
print (files)
print ('--------------------------------')
Python3
# Python program to explain os.path.join() method
# importing os module
import os
# Path
path = "/home"
# Join various path components
print(os.path.join(path, "User/Desktop", "file.txt"))
# Path
path = "User/Documents"
# Join various path components
print(os.path.join(path, "/home", "file.txt"))
# In above example '/home'
# represents an absolute path
# so all previous components i.e User / Documents
# are thrown away and joining continues
# from the absolute path component i.e / home.
# Path
path = "/home"
# Join various path components
print(os.path.join(path, "User/Public/", "Documents", ""))
# In above example the last
# path component is empty
# so a directory separator ('/')
# will be put at the end
# along with the concatenated value
Python3
# Python program to explain os.makedirs() method
# importing os module
import os
# Leaf directory
directory = "nikhil"
# Parent Directories
parent_dir = "/home/User/Documents/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'ihritik'
os.makedirs(path)
print("Directory '%s' created" %directory)
Python3
# Python program to explain shutil.copy2() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = '/home/nikhil/Desktop/new'
# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))
# Source path
source = "/home/nikhil/Desktop/new/pdf.py"
# Print the metadeta
# of source file
metadata = os.stat(source)
print("Metadata:", metadata, "\n")
# Destination path
destination = "/home/nikhil/Desktop/new/copy_pdf.py"
# Copy the content of
# source to destination
dest = shutil.copy2(source, destination)
# List files and directories
# in "/home / User / Documents"
print("After copying file:")
print(os.listdir(path))
# Print the metadata
# of the destination file
matadata = os.stat(destination)
print("Metadata:", metadata)
# Print path of newly
# created file
print("Destination path:", dest)
Python3
# Python program to explain shutil.move() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = '/home/nikhil/Desktop/'
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before moving file:")
print(os.listdir(path))
# Source path
source = '/home/nikhil/Desktop/new'
# Destination path
destination = '/home/nikhil/Desktop/new2'
# Move the content of
# source to destination
dest = shutil.move(source, destination)
# List files and directories
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks"
print("After moving file:")
print(os.listdir(path))
# Print path of newly
# created file
print("Destination path:", dest)
Python3
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file.txt'
# File location
location = "/home/User/Documents"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
print("%s has been removed successfully" %file)
Python3
# Python program to demonstrate
# shutil.rmtree()
import shutil
import os
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
# directory
dir = "Authors"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)
输出:
Current working directory: /home/nikhil/Desktop/gfg
os.chdir()
Python中的 os.chdir() 方法用于将当前工作目录更改为指定路径。它只需要一个参数作为新的目录路径。
Python3
# Python3 program to change the
# directory of file using os.chdir() method
# import os library
import os
# change the current directory
# to specified directory
os.chdir(r"C:\Users\Gfg\Desktop\geeks")
print("Directory changed")
输出:
Directory changed
os.listdir()
Python中的os.listdir()方法用于获取指定目录下所有文件和目录的列表。如果我们不指定任何目录,则将返回当前工作目录中的文件和目录列表。
例子:
Python3
# Python program to explain os.listdir() method
# importing os module
import os
# Get the path of current working directory
path = '/home'
# Get the list of all files and directories
# in current working directory
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
print(dir_list)
输出:
Files and directories in ' /home ' :
['nikhil']
os.walk()
os.walk() 通过自上而下或自下而上遍历树来生成目录树中的文件名。对于以目录 top 为根的树中的每个目录(包括 top 本身),它会产生一个 3 元组(dirpath、dirnames、filenames)。
例子:
Python3
# Driver function
import os
for (root,dirs,files) in os.walk('/home/nikhil/Desktop/', topdown=True):
print (root)
print (dirs)
print (files)
print ('--------------------------------')
输出:
os.path.join()
Python中的 os.path.join() 方法智能地连接一个或多个路径组件。此方法将各种路径组件与除了最后一个路径组件之外的每个非空部分之后的每个非空部分都使用一个目录分隔符 ('/') 连接。如果要加入的最后一个路径组件为空,则将目录分隔符 ('/') 放在末尾。
Python3
# Python program to explain os.path.join() method
# importing os module
import os
# Path
path = "/home"
# Join various path components
print(os.path.join(path, "User/Desktop", "file.txt"))
# Path
path = "User/Documents"
# Join various path components
print(os.path.join(path, "/home", "file.txt"))
# In above example '/home'
# represents an absolute path
# so all previous components i.e User / Documents
# are thrown away and joining continues
# from the absolute path component i.e / home.
# Path
path = "/home"
# Join various path components
print(os.path.join(path, "User/Public/", "Documents", ""))
# In above example the last
# path component is empty
# so a directory separator ('/')
# will be put at the end
# along with the concatenated value
/home/User/Desktop/file.txt
/home/file.txt
/home/User/Public/Documents/
os.makedirs()
Python中的 os.makedirs() 方法用于递归创建目录。这意味着如果缺少任何中间级目录,则在创建叶目录时, os.makedirs() 方法将全部创建它们。例如考虑以下路径:
/home/User/Documents/GeeksForGeeks/Authors/nikhil
假设我们要创建一个目录“nikhil”,但路径中的目录“GeeksForGeeks”和“Authors”不可用。然后 os.makedirs() 方法将在指定路径中创建所有不可用/丢失的目录。将首先创建“GeeksForGeeks”和“Authors”,然后创建“nikhil”目录。
例子:
Python3
# Python program to explain os.makedirs() method
# importing os module
import os
# Leaf directory
directory = "nikhil"
# Parent Directories
parent_dir = "/home/User/Documents/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'ihritik'
os.makedirs(path)
print("Directory '%s' created" %directory)
输出:
Directory 'nikhil' created
shutil.copy2()
Python中的 shutil.copy2() 方法用于将源文件的内容复制到目标文件或目录。此方法与 shutil.copy() 方法相同,但它也尝试保留文件的元数据。
例子:
使用的目录
Python3
# Python program to explain shutil.copy2() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = '/home/nikhil/Desktop/new'
# List files and directories
# in '/home/User/Documents'
print("Before copying file:")
print(os.listdir(path))
# Source path
source = "/home/nikhil/Desktop/new/pdf.py"
# Print the metadeta
# of source file
metadata = os.stat(source)
print("Metadata:", metadata, "\n")
# Destination path
destination = "/home/nikhil/Desktop/new/copy_pdf.py"
# Copy the content of
# source to destination
dest = shutil.copy2(source, destination)
# List files and directories
# in "/home / User / Documents"
print("After copying file:")
print(os.listdir(path))
# Print the metadata
# of the destination file
matadata = os.stat(destination)
print("Metadata:", metadata)
# Print path of newly
# created file
print("Destination path:", dest)
输出:
Before copying file:
[‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
After copying file:
[‘copy_pdf.py’, ‘pdf.py’, ‘pdf1.pdf’]
Metadata: os.stat_result(st_mode=33204, st_ino=58068385, st_dev=2050, st_nlink=1, st_uid=1000, st_gid=1000, st_size=887, st_atime=1619538642, st_mtime=1618307699, st_ctime=1618307700)
Destination path: /home/nikhil/Desktop/new/copy_pdf.py
目录
shutil.move()
shutil.move() 方法 递归地将文件或目录(源)移动到另一个位置(目标)并返回目标。如果目标目录已经存在,则将 src 移动到该目录中。如果目标已经存在但不是目录,那么它可能会根据 os.rename() 语义被覆盖。
例子:
使用的目录
Python3
# Python program to explain shutil.move() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = '/home/nikhil/Desktop/'
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before moving file:")
print(os.listdir(path))
# Source path
source = '/home/nikhil/Desktop/new'
# Destination path
destination = '/home/nikhil/Desktop/new2'
# Move the content of
# source to destination
dest = shutil.move(source, destination)
# List files and directories
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks"
print("After moving file:")
print(os.listdir(path))
# Print path of newly
# created file
print("Destination path:", dest)
输出:
os.remove()
Python中的 os.remove() 方法用于删除或删除文件路径。此方法不能删除或删除目录。
例子:
Python3
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file.txt'
# File location
location = "/home/User/Documents"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
print("%s has been removed successfully" %file)
输出:
file.txt has been removed successfully
shutil.rmtree()
shutil.rmtree() 用于删除整个目录树,路径必须指向一个目录。
示例:假设目录和子目录如下。
# 父目录:
# 父目录内的目录:
# 子目录下的文件:
Python3
# Python program to demonstrate
# shutil.rmtree()
import shutil
import os
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
# directory
dir = "Authors"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)
输出:
Refer to the below articles for our complete tutorial on the OS module and Shutil module.
- OS Module in Python with Examples
- Shutil Module in Python