python中幾個實用的檔案操作

2021-08-18 22:39:59 字數 1733 閱讀 7140

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

os.path.exists(input_folder)

2. 判斷指定目錄是不是資料夾

os.path.isdir(input_folder)

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

os.path.isfile(input_folder)

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

import imghdr

img_list=

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

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" % './'.format(input_pathof_fileordir))

Linux中的幾個實用技巧

一 vim 儲存乙個沒有許可權的已編輯檔案 剛安裝好ubuntu,用vim對vim etc ssh sshd config檔案做了更改,儲存時才發現對該檔案僅有唯讀許可權,不能進行儲存操作。告警內容如下 解決方法1 把檔案關閉,獲取許可權以後再重新開啟。但是如果你已經做了大量更改,這樣做會很浪費時間...

python中13個實用的檔案操作

1.判斷指定目錄是否存在 os.path.exists input folder 2.判斷指定目錄是不是資料夾 os.path.isdir input folder 3.判斷指定目錄是不是檔案 os.path.isfile input folder 4.判斷指定檔案是不是 判斷給定檔案是何種型別 i...

python通用序列操作 序列的幾個通用操作介紹

sequence 是 python 的一種內建型別 built in type 內建型別就是構建在 python interpreter 裡面的型別,幾個基本的 sequence type 比如 list 表 tuple 定值表,或翻譯為元組 range 範圍 可以看作是 python interp...