python 部分文件、目錄操作

獲取當前目錄名

path = getcwd()

示例:

import os
path = os.getcwd()
print(path)

輸出

D:\專業文檔\learnpython\自用\整理目錄

創建目錄

示例
improt os
os.mkdir(‘D:\專業文檔\temp’)


刪除目錄

示例

os.rmdir('D:\\專業文檔\\temp')

創建新空白文件

示例:

os.mknod('test.txt')

複製文件:

shutil.copyfile()       

複製文件夾:

shutil.copytree()   

重命名文件(目錄)

os.rename("oldname","newname") 

移動文件(目錄)

shutil.move() 
語法:
shutil.move(src, dst, copy_function=copy2)
傳入參數

src ———- 需要移動的文件或目錄
dst ———- 目標

官方文檔

Recursively move a file or directory (src) to another location (dst) and return the destination.
If the destination is an existing directory, then src is moved inside that directory. If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dstusing copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.
If copy_function is given, it must be a callable that takes two arguments src and dst, and will be used to copy src to dest if os.rename() cannot be used. If the source is a directory, copytree() is called, passing it the copy_function(). The default copy_function is copy2(). Using copy() as the copy_function allows the move to succeed when it is not possible to also copy the metadata, at the expense of not copying any of the metadata.
Changed in version 3.3: Added explicit symlink handling for foreign filesystems, thus adapting it to the behavior of GNU’s mv. Now returns dst.
Changed in version 3.5: Added the copy_function keyword argument.


刪除文件

os.remove()

刪除空目錄

os.rmdir()

刪除目錄

shutil.rmtree("dir")    

轉換目錄

os.chdir("path")    

判斷對象是否存在

os.path.exists("goal") 
官方文檔

Return True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to executeos.stat() on the requested file, even if the path physically exists.
Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.
Changed in version 3.6: Accepts a path-like object.


判斷對象是否是目錄

os.path.isdir("goal")    

判斷對象是否是文件

os.path.isfile("goal")    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章