Python中的 OS 模块和示例
Python中的 OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 *os* 和 *os.path* 模块包含许多与文件系统交互的函数。
处理当前工作目录
将当前工作目录(CWD)视为Python正在运行的文件夹。每当文件仅以其名称调用时, Python假定它以 CWD 开头,这意味着仅名称引用只有在文件位于 Python 的 CWD 中时才会成功。
注意:运行Python脚本的文件夹称为当前目录。这不是Python脚本所在的路径。
获取当前工作目录
使用 os.getcwd() 获取当前工作目录的位置。
例子:
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
# Python program to change the
# current working directory
import os
# Function to Get the current
# working directory
def current_path():
print("Current working directory before")
print(os.getcwd())
print()
# Driver's code
# Printing CWD before
current_path()
# Changing the CWD
os.chdir('../')
# Printing CWD after
current_path()
Python3
# Python program to explain os.mkdir() method
# importing os module
import os
# Directory
directory = "GeeksforGeeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
# Directory
directory = "Geeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects"
# mode
mode = 0o666
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
# with mode 0o666
os.mkdir(path, mode)
print("Directory '% s' created" % directory)
Python3
# Python program to explain os.makedirs() method
# importing os module
import os
# Leaf directory
directory = "Nikhil"
# Parent Directories
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Nikhil'
os.makedirs(path)
print("Directory '% s' created" % directory)
# Directory 'GeeksForGeeks' and 'Authors' will
# be created too
# if it does not exists
# Leaf directory
directory = "c"
# Parent Directories
parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"
# mode
mode = 0o666
path = os.path.join(parent_dir, directory)
# Create the directory 'c'
os.makedirs(path, mode)
print("Directory '% s' created" % directory)
# 'GeeksForGeeks', 'a', and 'b'
# will also be created if
# it does not exists
# If any of the intermediate level
# directory is missing
# os.makedirs() method will
# create them
# os.makedirs() method can be
# used to create a directory tree
Python3
# Python program to explain os.listdir() method
# importing os module
import os
# Get the list of all files and directories
# in the root directory
path = "/"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# print the list
print(dir_list)
Python3
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file1.txt'
# File location
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
e)
Python3
# Python program to explain os.rmdir() method
# importing os module
import os
# Directory name
directory = "Geeks"
# Parent Directory
parent = "D:/Pycharm projects/"
# Path
path = os.path.join(parent, directory)
# Remove the Directory
# "Geeks"
os.rmdir(path)
Python3
import os
print(os.name)
Python3
import os
try:
# If the file does not exist,
# then it would throw an IOError
filename = 'GFG.txt'
f = open(filename, 'rU')
text = f.read()
f.close()
# Control jumps directly to here if
# any of the above lines throws IOError.
except IOError:
# print(os.error) will
print('Problem reading: ' + filename)
# In any case, the code then continues with
# the line after the try/except
Python3
import os
fd = "GFG.txt"
# popen() is similar to open()
file = open(fd, 'w')
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)
# popen() provides a pipe/gateway and accesses the file directly
file = os.popen(fd, 'w')
file.write("Hello")
# File not closed, shown in next function.
Python3
import os
fd = "GFG.txt"
file = open(fd, 'r')
text = file.read()
print(text)
os.close(file)
Python
import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')
Python3
import os #importing os module.
os.remove("file_name.txt") #removing the file.
Python3
import os
#importing os module
result = os.path.exists("file_name") #giving the name of the file as a parameter.
print(result)
Python3
import os #importing os module
size = os.path.getsize("filename")
print("Size of the file is", size," bytes.")
输出:
Current working directory: /home/nikhil/Desktop/gfg
更改当前工作目录
要更改当前工作目录(CWD),请使用 os.chdir() 方法。此方法将 CWD 更改为指定路径。它只需要一个参数作为新的目录路径。
注意:当前工作目录是运行Python脚本的文件夹。
例子:
Python3
# Python program to change the
# current working directory
import os
# Function to Get the current
# working directory
def current_path():
print("Current working directory before")
print(os.getcwd())
print()
# Driver's code
# Printing CWD before
current_path()
# Changing the CWD
os.chdir('../')
# Printing CWD after
current_path()
输出:
Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg
Current working directory after
C:\Users\Nikhil Aggarwal\Desktop
创建目录
OS 模块中有不同的方法可用于创建目录。这些都是 -
- os.mkdir()
- os.makedirs()
使用 os.mkdir()
Python中的 os.mkdir() 方法用于以指定的数字模式创建名为 path 的目录。如果要创建的目录已经存在,则此方法引发 FileExistsError。
例子:
Python3
# Python program to explain os.mkdir() method
# importing os module
import os
# Directory
directory = "GeeksforGeeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
# Directory
directory = "Geeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects"
# mode
mode = 0o666
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
# with mode 0o666
os.mkdir(path, mode)
print("Directory '% s' created" % directory)
输出:
Directory 'GeeksforGeeks' created
Directory 'Geeks' created
使用 os.makedirs()
Python中的 os.makedirs() 方法用于递归创建目录。这意味着如果缺少任何中间级目录,则在创建叶目录时, os.makedirs() 方法将全部创建它们。
例子:
Python3
# Python program to explain os.makedirs() method
# importing os module
import os
# Leaf directory
directory = "Nikhil"
# Parent Directories
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Nikhil'
os.makedirs(path)
print("Directory '% s' created" % directory)
# Directory 'GeeksForGeeks' and 'Authors' will
# be created too
# if it does not exists
# Leaf directory
directory = "c"
# Parent Directories
parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"
# mode
mode = 0o666
path = os.path.join(parent_dir, directory)
# Create the directory 'c'
os.makedirs(path, mode)
print("Directory '% s' created" % directory)
# 'GeeksForGeeks', 'a', and 'b'
# will also be created if
# it does not exists
# If any of the intermediate level
# directory is missing
# os.makedirs() method will
# create them
# os.makedirs() method can be
# used to create a directory tree
输出:
Directory 'Nikhil' created
Directory 'c' created
使用Python列出文件和目录
Python中的os.listdir()方法用于获取指定目录下所有文件和目录的列表。如果我们不指定任何目录,那么将返回当前工作目录中的文件和目录列表。
例子:
Python3
# Python program to explain os.listdir() method
# importing os module
import os
# Get the list of all files and directories
# in the root directory
path = "/"
dir_list = os.listdir(path)
print("Files and directories in '", path, "' :")
# print the list
print(dir_list)
输出:
Files and directories in ' / ' :
['sys', 'run', 'tmp', 'boot', 'mnt', 'dev', 'proc', 'var', 'bin', 'lib64', 'usr',
'lib', 'srv', 'home', 'etc', 'opt', 'sbin', 'media']
使用Python删除目录或文件
OS 模块证明了在Python中删除目录和文件的不同方法。这些都是 -
- 使用 os.remove()
- 使用 os.rmdir()
使用 os.remove()
Python中的 os.remove() 方法用于删除或删除文件路径。此方法不能删除或删除目录。如果指定的路径是目录,则该方法将引发 OSError。
示例:假设文件夹中包含的文件是:
Python3
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file1.txt'
# File location
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
e)
输出:
使用 os.rmdir()
Python中的 os.rmdir() 方法用于删除或删除一个空目录。如果指定的路径不是空目录,将引发 OSError。
示例:假设目录是
Python3
# Python program to explain os.rmdir() method
# importing os module
import os
# Directory name
directory = "Geeks"
# Parent Directory
parent = "D:/Pycharm projects/"
# Path
path = os.path.join(parent, directory)
# Remove the Directory
# "Geeks"
os.rmdir(path)
输出:
常用函数
1. os.name:该函数给出了导入的操作系统依赖模块的名称。当前已注册以下名称:“posix”、“nt”、“os2”、“ce”、“Java”和“riscos”。
Python3
import os
print(os.name)
输出:
posix
注意:当您在此处运行代码时,它可能会在不同的解释器上给出不同的输出,例如“posix”。
2. os.error:此模块中的所有函数在文件名和路径无效或不可访问的情况下,或其他具有正确类型但操作系统不接受的参数的情况下都会引发 OSError。 os.error 是内置 OSError 异常的别名。
Python3
import os
try:
# If the file does not exist,
# then it would throw an IOError
filename = 'GFG.txt'
f = open(filename, 'rU')
text = f.read()
f.close()
# Control jumps directly to here if
# any of the above lines throws IOError.
except IOError:
# print(os.error) will
print('Problem reading: ' + filename)
# In any case, the code then continues with
# the line after the try/except
输出:
Problem reading: GFG.txt
3. os.popen():这个方法打开一个到或来自命令的管道。根据模式是“r”还是“w”,可以读取或写入返回值。
句法:
os.popen(command[, mode[, bufsize]])
参数 mode 和 bufsize 不是必需参数,如果不提供,则默认 'r' 为模式。
Python3
import os
fd = "GFG.txt"
# popen() is similar to open()
file = open(fd, 'w')
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)
# popen() provides a pipe/gateway and accesses the file directly
file = os.popen(fd, 'w')
file.write("Hello")
# File not closed, shown in next function.
输出:
Hello
注意: popen() 的输出不会显示,文件会直接更改。
4. os.close():关闭文件描述符fd。使用 open() 打开的文件只能通过 close() 关闭。但是通过 os.popen() 打开的文件,可以用 close() 或 os.close() 关闭。如果我们尝试关闭使用 open() 打开的文件,使用 os.close(), Python会抛出 TypeError。
Python3
import os
fd = "GFG.txt"
file = open(fd, 'r')
text = file.read()
print(text)
os.close(file)
输出:
Traceback (most recent call last):
File "C:\Users\GFG\Desktop\GeeksForGeeksOSFile.py", line 6, in
os.close(file)
TypeError: an integer is required (got type _io.TextIOWrapper)
注意:由于不存在的文件或权限权限,可能不会抛出相同的错误。
5. os.rename():文件 old.txt 可以重命名为 new.txt,使用函数os.rename()。只有当文件存在并且用户有足够的权限来更改文件时,文件的名称才会更改。
Python
import os
fd = "GFG.txt"
os.rename(fd,'New.txt')
os.rename(fd,'New.txt')
输出:
Traceback (most recent call last):
File "C:\Users\GFG\Desktop\ModuleOS\GeeksForGeeksOSFile.py", line 3, in
os.rename(fd,'New.txt')
FileNotFoundError: [WinError 2] The system cannot find the
file specified: 'GFG.txt' -> 'New.txt'
理解输出:存在一个文件名“GFG.txt”,因此当第一次使用 os.rename() 时,文件被重命名。第二次调用函数os.rename() 时,文件“New.txt”存在而不是“GFG.txt”
因此Python抛出 FileNotFoundError。
6. os.remove():使用 Os 模块,我们可以使用 remove() 方法删除系统中的文件。要删除文件,我们需要将文件名作为参数传递。
Python3
import os #importing os module.
os.remove("file_name.txt") #removing the file.
OS 模块在我们和操作系统之间提供了一个抽象层。当我们使用 os 时 模块始终根据操作系统指定绝对路径,代码可以在任何操作系统上运行,但我们需要准确更改路径。如果您尝试删除不存在的文件,您将收到FileNotFoudError 。
7. os.path.exists():该方法将通过传递文件名作为参数来检查文件是否存在。 OS 模块有一个名为 PATH 的子模块,通过它我们可以执行更多功能。
Python3
import os
#importing os module
result = os.path.exists("file_name") #giving the name of the file as a parameter.
print(result)
False
如上面的代码,文件不存在它会输出 False。如果文件存在,它将给我们输出 True。
8. os.path.getsize():在这个方法中, Python会给我们以字节为单位的文件大小。要使用此方法,我们需要将文件名作为参数传递。
Python3
import os #importing os module
size = os.path.getsize("filename")
print("Size of the file is", size," bytes.")
输出:
Size of the file is 192 bytes.