python中的OS模块提供了与操作系统交互的功能。操作系统,属于Python的标准实用程序模块。该模块提供了一种使用操作系统相关功能的便携方式。* os *和* os.path *模块包含许多与文件系统交互的函数。
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.








暂无数据