Python中的OS模块提供了与操作系统交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了一种使用操作系统相关功能的便携方式。操作系统。path*模块包括许多与文件系统交互的功能。
处理当前工作目录
考虑 当前工作目录(CWD) 作为一个文件夹,Python在其中运行。每当只按文件名调用文件时,Python都假定它从CWD中开始,这意味着只有当文件位于Python的CWD中时,仅使用名称的引用才会成功。 注: 运行Python脚本的文件夹称为当前目录。这不是Python脚本所在的路径。 正在获取当前工作目录 获取当前工作目录的位置 操作系统。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) |
输出:
Current working directory: /home/nikhil/Desktop/gfg
更改当前工作目录(CWD)的步骤 操作系统。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 beforeC:UsersNikhil AggarwalDesktopgfgCurrent working directory afterC:UsersNikhil AggarwalDesktop
创建目录
操作系统模块中有不同的创建目录的方法。这些是——
- 操作系统。mkdir()
- 操作系统。makedirs()
使用操作系统。mkdir()
操作系统。Python中的mkdir()方法用于以指定的数字模式创建名为path的目录。如果要创建的目录已存在,此方法将引发FileExistError。
例子:
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' createdDirectory 'Geeks' created
使用操作系统。makedirs()
操作系统。Python中的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' createdDirectory 'c' created
用Python列出文件和目录
操作系统。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中删除目录和文件的不同方法。这些是——
- 使用操作系统。删除()
- 使用操作系统。rmdir()
使用操作系统。删除()
操作系统。Python中的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) |
输出:
使用操作系统。rmdir()
操作系统。Python中的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.操作系统。姓名: 此函数提供导入的操作系统相关模块的名称。以下名称目前已注册:“posix”、“nt”、“os2”、“ce”、“java”和“riscos”。
Python3
import os print (os.name) |
输出:
posix
注: 在这里运行代码时,它可能会在不同的解释器上提供不同的输出,例如“posix”。
2.操作系统。错误: 如果文件名和路径无效或无法访问,或者其他参数类型正确,但操作系统不接受,则此模块中的所有函数都会引发OSError。操作系统。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 <class 'OSError'> print ( 'Problem reading: ' + filename) # In any case, the code then continues with # the line after the try/except |
输出:
Problem reading: GFG.txt
3.操作系统。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.操作系统。关闭(): 关闭文件描述符fd。使用open()打开的文件只能通过close()关闭。但文件是通过操作系统打开的。popen(),可以使用close()或os关闭。close()。如果我们尝试使用os关闭用open()打开的文件。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:UsersGFGDesktopGeeksForGeeksOSFile.py", line 6, in os.close(file)TypeError: an integer is required (got type _io.TextIOWrapper)
注: 由于文件或权限不存在,可能不会引发相同的错误。
5.操作系统。重命名(): 一个旧文件。txt可以重新命名为new。txt,使用os函数。重命名()。只有当文件存在且用户有足够的权限更改文件时,文件名才会更改。
python
import os fd = "GFG.txt" os.rename(fd, 'New.txt' ) os.rename(fd, 'New.txt' ) |
输出:
Traceback (most recent call last): File "C:UsersGFGDesktopModuleOSGeeksForGeeksOSFile.py", line 3, in os.rename(fd,'New.txt')FileNotFoundError: [WinError 2] The system cannot find thefile specified: 'GFG.txt' -> 'New.txt'
理解输出: 文件名“GFG.txt”存在,因此当操作系统。第一次使用rename()时,文件将被重命名。在调用函数os时。重命名()第二次,文件“New.txt”存在,而不是“GFG.txt” 因此Python抛出FileNotFoundError。
6.操作系统。删除(): 使用Os模块,我们可以使用remove()方法删除系统中的文件。要删除文件,我们需要将文件名作为参数传递。
Python3
import os #importing os module. os.remove( "file_name.txt" ) #removing the file. |
操作系统模块在我们和操作系统之间提供了一个抽象层。当我们使用os时 模块总是根据操作系统指定绝对路径。代码可以在任何操作系统上运行,但我们需要精确地更改路径。如果你试图删除一个不存在的文件,你会得到 FileNotFoudError .
7.操作系统。路径存在(): 此方法将通过将文件名作为参数传递来检查文件是否存在。操作系统模块有一个名为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.操作系统。路径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.
本文由 皮尤斯门战 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。