本文共 10409 字,大约阅读时间需要 34 分钟。
python中os函数
Python OS module allows us to use the operating system dependent functionalities and to interact with the underlying operating system in several different ways. For example, we can work with files, change the environment variables, and we can move files around, etc. This is as same as overriding all the os built-in functionalities in a module and using them in a file I/O and system handling.
Python OS模块允许我们使用依赖于操作系统的功能,并以几种不同的方式与基础操作系统进行交互。 例如,我们可以处理文件,更改环境变量,可以移动文件等。这与覆盖模块中的所有os内置功能以及在文件I / O和系统中使用它们相同。处理。
Now, as it is a built-in module, so we don’t have to install any third-party libraries. We can import the os module in our program like this:
现在,由于它是一个内置模块,因此我们不必安装任何第三方库。 我们可以像这样将os模块导入程序中:
import os # importing the complete os modulefrom os import name # importing a variable from the os module
Let’s look at a simple example of using the os module.
让我们看一个使用os模块的简单示例。
Code:
码:
import osprint(dir(os))
Output:
输出:
NOTE: By printing this built-in dir() function and pass the os module, it shows us all of the attributes and methods that we have access to within this module.
注意:通过打印此内置dir()函数并传递os模块,它向我们显示了我们可以在此模块中访问的所有属性和方法。
OS module provides some callable methods and some variables. Some of the common methods for different functional categories are:
OS模块提供了一些可调用的方法和一些变量。 用于不同功能类别的一些常用方法是:
print(os.name)
Output:
输出:
import ostry: filename = 'abcd2.txt' f = open(filename, 'r') text = f.read() f.close()except os.error: print('Problem reading: ' + filename)
Output:
输出:
cmd = "git --version"returned_value = os.system(cmd) # returns the exit code in unixprint('returned value:', returned_value)
OUTPUT: 输出:import osos.chdir('C:/Users/user/Desktop/temp')# returns all the environment variablesprint(os.environ)# to get in particularprint(os.environ.get('TEMP'))
OUTPUT:
输出:
print(os.getcwd())
OUTPUT: C:\Users\user\.PyCharmCE2017.3\config\scratches
输出: C:\Users\user\.PyCharmCE2017.3\config\scratches
os.chdir('C:/Users/user/.PyCharmCE2017.3/')print(os.getcwd())
OUTPUT: C:\Users\user\.PyCharmCE2017.3
输出: C:\Users\user\.PyCharmCE2017.3
print(os.listdir())
OUTPUT: ['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'afcat',]
输出 : ['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'afcat',]
import osfd = "abc.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()and accesses the file directlyfile = os.popen(fd, 'w')file.write("Hello")
OUTPUT:
输出:
Note: It must be applied to a file descriptor returned by os.open() or pipe() built-in functions of os module.
注意:必须将其应用于os模块的os.open()或pipe()内置函数返回的文件描述符。
fd = "abc.txt"file = open(fd, 'r')text = file.read()print(text)os.close(file)
OUTPUT:
输出:
NOTE: Error is thrown for the non-existence of the file or the permission privileges.
注意 :由于文件不存在或权限特权而引发错误。
print(os.stat('abcd1'))# for some simplified and particular details# we can use dot operator and that attribute name# this returns the timestamp of last modification timeprint(os.stat('abcd1').st_mtime)# this returns the size of the file in bytesprint(os.stat('abcd1').st_size)
OUTPUT:
输出:
os.chdir('C:/Users/user/Desktop/temp')# returns a 3-tuplefor dirpath, dirname, filename in os.walk('C:/Users/user/Desktop/temp'): print('Current path: ',dirpath) print('Directories: ', dirname) print('Files: ', filename) print()
OUTPUT:
输出:
Differences: makedirs() creates all the intermediate directories if they don’t exist already and mkdir() can create a single sub-directory and will throw an exception if intermediate directories that don’t exist are specified.
区别 :makedirs()创建所有中间目录(如果尚不存在),而mkdir()可以创建单个子目录,并且如果指定了不存在的中间目录,则将引发异常。
OUTPUT:
输出:
['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'abcd', 'abcd1', 'afcat',]Traceback (most recent call last):File "C:/Users/user/.PyCharmCE2017.3/config/scratches/scratch.py", line 18, inos.mkdir('abcd2/subdir')FileNotFoundError: [WinError 3] The system cannot find the path specified: 'abcd2/subdir'['.git', '1802.04103.pdf', '1st year', '2K16-CO-200', 'abc.txt', 'abcd', 'abcd1', 'abcd2', 'afcat']Process finished with exit code 1
NOTE: The line 18 code thrown an error for creating a directory along with a subdirectory because os.mkdir() don’t work in a tree fashion.
注意 :第18行代码在创建目录和子目录时引发错误,因为os.mkdir()不能以树的形式工作。
os.rmdir('abcd')os.removedirs('abcd2/subdir')print(os.listdir())
OUTPUT: [‘.git’, ‘1802.04103.pdf’, ‘1st year’, ‘2K16-CO-200’, ‘abc.txt’, ‘abcd1’, , ‘afcat’]
输出: ['.git','1802.04103.pdf','1st year','2K16-CO-200','abc.txt','abcd1','afcat']
os.chdir('C:/Users/user/Desktop/temp')print(os.listdir())os.rename('xyz.txt','abc.txt')print(os.listdir())
OUTPUT:
输出:
import osos.chdir('C:/Users/user/Desktop/temp')print(os.listdir())os.chdir('C:/Users/user/Desktop/')os.remove('temp/abc.txt')os.chdir('C:/Users/user/Desktop/temp')print(os.listdir())
OUTPUT:
输出:
At this point will be familiar with the python os module. In this article, we learned the following:
至此,您将熟悉python os模块。 在本文中,我们了解了以下内容:
There are a lot of other functions in the os module that has not been discussed here because they are not commonly used. Be sure to read the documentation to see what else you can do with the python os module
os模块中还有许多其他功能在这里没有讨论,因为它们不常用。 请务必阅读文档以了解python os模块还可以做什么。
翻译自:
python中os函数
转载地址:http://htlzd.baihongyu.com/