python中的OS模块提供了与操作系统交互的功能。OS属于Python的标准实用程序模块。此模块提供了使用操作系统相关功能的便捷方式。os和os.path模块包含许多与文件系统交互的函数。
以下是OS模块中的一些功能:
1)os.name:此函数提供导入的与操作系统相关的模块的名称。当前已注册以下名称:‘posix’, ‘nt’, ‘os2’, ‘ce’, ‘java’ and ‘riscos’
import os
print(os.name)
输出:
posix
注意:在此处运行代码时,它可能在不同的解释器上提供不同的输出,例如“posix”。
2)os.getcwd():函数os.getcwd(),返回用于执行代码的文件的当前工作目录(CWD),这可能因系统而异。
import os
print(os.getcwd())
# To print absolute path on your system
# os.path.abspath('.')
# To print files and directories in the current directory
# on your system
# os.listdir('.')
输出:
C:\Users\GFG\Desktop\ModuleOS
注意:对于GFG解释器,使用的目录为\ root。
3)os.error:如果文件名和路径无效或无法访问,或者具有正确类型但操作系统不接受的其他参数,则此模块中的所有函数都会引发OSError。 os.error是内置OSError异常的别名。
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
文件对象操作
4)os.popen():此方法打开与命令之间的管道。根据模式是“r”还是“w”,可以读取或写入返回值。
语法:
os.popen(command[, mode[, bufsize]])
参数mode&bufsize不是必需的参数,如果未提供,则将模式默认为“ r”。
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()的输出,会直接更改文件。
5)os.close():关闭文件描述符fd。使用open()打开的文件只能通过close()关闭。但是,通过os.popen()打开的文件可以使用close()或os.close()关闭。如果我们尝试使用os.close()关闭用open()打开的文件,Python将抛出TypeError。
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)
注意:由于文件或权限特权不存在,可能不会引发相同的错误。
6)os.rename():可以使用函数os.rename()将文件old.txt重命名为new.txt。只有当文件存在且用户有足够权限允许更改文件时,文件的名称才会更改。
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'
理解输出:文件名“GF.txt”存在,因此当第一次使用OS.RealMeMe()时,文件将被重命名。在调用函数OS.RealMeMe()第二次时,文件“NeX.txt”存在而不是“gfg.txt”。因此,Python抛出FileNotFoundError。