python 查看文件名和文件路徑


查看文件名和文件路徑

復制代碼
1 >>> import os
2 >>> url = 'https://images0.cnblogs.com/i/311516/201403/020013141657112.png'
3 >>> filename = os.path.basename(url)
4 >>> filepath = os.path.dirname(url)
5 >>> filename 
6 '020013141657112.png'
7 >>> filepath
8 'https://images0.cnblogs.com/i/311516/201403'
9 >>> 
復制代碼

 

1 import os
2 print(os.path.realpath(__file__))    # 當前文件的路徑
3 print(os.path.dirname(os.path.realpath(__file__)))  # 從當前文件路徑中獲取目錄
4 print(os.path.basename(os.path.realpath(__file__))) # 從當前文件路徑中獲取文件名

 

1 print(os.listdir(dirname))     # 只顯示該目錄下的文件名和目錄名,不包含子目錄中的文件,默認為當前文件所在目錄

 

復制代碼
 1 import os
 2 
 3 # os.walk()遍歷文件夾下的所有文件
 4 # os.walk()獲得三組數據(rootdir, dirname,filnames)
 5 def file_path(file_dir):
 6     for root, dirs, files in os.walk(file_dir):
 7         print(root, end=' ')    # 當前目錄路徑
 8         print(dirs, end=' ')    # 當前路徑下的所有子目錄
 9         print(files)            # 當前目錄下的所有非目錄子文件
復制代碼
 
 
===============================================================================

以下是把sourceDir目錄下的以.JPG結尾的文件所有拷貝到targetDir目錄下:

 

<span style="font-size:18px;">>>>import os
>>> import os.path
>>> import shutil 
>>> def copyFiles(sourceDir,targetDir):
	for files in os.listdir(sourceDir):
		sourceFile = os.path.join(sourceDir,files)   //把文件夾名和文件名稱鏈接起來
		targetFile = os.path.join(targetDir,files)
		if os.path.isfile(sourceFile) and sourceFile.find('.JPG')>0: //要求是文件且后綴是jpg

 

shutil模塊

復制文件夾

復制文件

復制文件的時候。假設指定的文件目的位置之間有文件夾不存在。則會拋出錯誤。

所以最好在拷貝之間確認文件夾存在。

 

當文件夾存在的時候,復制文件就沒有問題了。

 

刪除文件夾使用例如以下函數:

shutil.rmtree('d:/dd')

移動文件或者目錄到另外一個地方:

shutil.move('d:/c.png','e:/')

-------------------------------------------

那么存在一個問題就是。copy函數和copyfile函數二者的差別是什么呢?

看help:

從help中能夠看出來,copyfile不過把文件復制到目的文件。可是copy函數能夠把文件的mode也一起拷貝。比方說原來的文件有+x可運行權限,那么目的文件也會有可運行權限。


刪除一級文件夾下的全部文件:

 

<span style="font-size:18px;">def removeFileInFirstDir(targetDir): 
     for file in os.listdir(targetDir): 
         targetFile = os.path.join(targetDir,  file) 
         if os.path.isfile(targetFile): //僅僅刪除文件不刪除目錄
             os.remove(targetFile)</span>

文本內容的復制,把文件夾下的全部文件的內容都寫入到目標文件里:

 

 

<span style="font-size:18px;">def coverFiles(sourceDir,  targetDir): 
        for file in os.listdir(sourceDir): 
             sourceFile = os.path.join(sourceDir,  file) 
             targetFile = os.path.join(targetDir,  file) 
             #cover the files //復寫?
             if os.path.isfile(sourceFile): 
                 open(targetFile, "wb").write(open(sourceFile, "rb").read())</span>

<span style="font-size:18px;">def writeVersionInfo(targetDir): 
     open(targetDir, "wb").write("Revison:")</span>

使用python腳本進行文件的操作是非常方便的的。省卻非常多時間


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM