import os # It will throw a Permission error; that's why we have to change the current working directory. os.rmdir("d:\\newdir") os.chdir("..") os.rmdir("newdir")
os.error()
函数的作用是:定义操作系统级错误。在文件名和路径无效或不可访问的情况下,它会引发错误。
例
import os
try: # If file does not exist, # then it throw an IOError filename = 'Python.txt' f = open(filename, 'rU') text = f.read() f.close()
# The Control jumps directly to here if # any lines throws IOError. except IOError:
# print(os.error) will <class 'OSError'> print('Problem reading: ' + filename)
输出:
Problem reading: Python.txt
os.popen()
此函数打开一个文件或从指定的命令,它返回一个连接到管道的文件对象。
例
import os fd = "python.txt"
# popen() is similar to open() file = open(fd, 'w') file.write("This is awesome") file.close() file = open(fd, 'r') text = file.read() print(text)
# popen() provides gateway and accesses the file directly file = os.popen(fd, 'w') file.write("This is awesome") # File not closed, shown in next function.
输出:
This is awesome
os.close()
该功能关闭描述符为 fr 的关联文件。
例
import os fr = "Python1.txt" file = open(fr, 'r') text = file.read() print(text) os.close(file)
输出:
Traceback (most recent call last): File "main.py", line 3, in file = open(fr, 'r') FileNotFoundError: [Errno 2] No such file or directory: 'Python1.txt'
os.rename()
可以使用 os.rename() 函数重命名文件或目录。如果用户有权更改文件,则可以重命名该文件。
例
import os fd = "python.txt" os.rename(fd,'Python1.txt') os.rename(fd,'Python1.txt')
输出:
Traceback (most recent call last): File "main.py", line 3, in os.rename(fd,'Python1.txt') FileNotFoundError: [Errno 2] No such file or directory: 'python.txt' -> 'Python1.txt'