天天看點

python中13個實用的檔案操作

1. 判斷指定目錄是否存在:

os.path.exists(input_folder)           

2. 判斷指定目錄是不是檔案夾

os.path.isdir(input_folder)           

3. 判斷指定目錄是不是檔案

os.path.isfile(input_folder)           

4. 判斷指定檔案是不是圖檔(判斷給定檔案是何種圖檔類型)

#Python學習交流QQ群:857662006 
import imghdr
img_list= {'jpg','bmp','png','jpeg','rgb','gif','pbm','ppm','tiff','xbm'}
if imghdr.what(input_filename) not in img_list:

print(not image)           

5. 判斷指定txt(檔案)是否為空

import os
if os.path.getsize('test.txt') is 0:
    print('test.txt is empty!')           

6. 按行讀取txt檔案内容

f = open('test.txt', "r")
lines = f.readlines()
for line in lines:
    print line
    line = line.strip('\n')  # 去掉換行符号 '\n'
    print line           

7. 周遊指定目錄檔案夾下所有檔案

for file in sorted(glob.glob(os.path.join(input_folder, '*.*'))):
    print(file)           

8. 在python程式中相容路徑中的中文符号

for file in sorted(glob.glob(os.path.join(input_folder, '*.*'))):

    file = unicode(file,'utf-8')           

9. 判斷檔案夾是否存在,不存在則建立,存在則删除後再建立:

if not os.path.exists('folder1'):
        os.makedirs('folder1')
else:
        shutil.rmtree('folder1')

        os.makedirs('folder1')           

10. 建立一個txt檔案并寫入,如果存在則清空後寫入:

f = open('test.txt', "wt")
f.writelines('test' + '\n')
f.close()           

11. 判斷路徑(字元串) path_str 中是否有中文字元:

# coding:utf-8
#Python學習交流QQ群:857662006
for ch in path_str.decode('utf-8'):

        if u'\u4e00' <= ch <= u'\u9fff':
            print('chinese character founded!')           

12. os.walk 周遊檔案夾下所有檔案(包括檔案夾下的檔案夾内檔案)

for root, dirs, files in os.walk(INPUT_FOLDER):
    for file in files:
        item = os.path.join(root,file)
        print(item)           

13. 在python程式中擷取檔案或檔案夾的絕對權限:

if os.path.exists(input_pathof_fileOrdir):

    os.system("chmod 777  %s" % './{0}'.format(input_pathof_fileOrdir))