13 practical file operations in python

1. Judge whether the specified directory exists:


2. Judge whether the specified directory is a folder


3. Judge whether the specified directory is a file


4. Determine whether the specified file is a picture (determine what kind of picture the given file is)

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. Judge whether the specified TXT (file) is empty

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

6. Read the contents of the txt file by line

f = open('test.txt', "r")
lines = f.readlines()
for line in lines:
    print line
    line = line.strip('\n')  # Remove newline '\ n'
    print line

7. Traverse all files under the specified directory folder

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

8. Chinese symbols in compatible paths in python programs

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

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

9. Judge whether the folder exists. If it does not exist, create it. If it exists, delete it and then create it

if not os.path.exists('folder1'):


10. Create a txt file and write it. If it exists, clear it and write it:

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

11. Judge whether there are Chinese characters in path (string):

# coding:utf-8
for ch in path_str.decode('utf-8'):

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

12. os.walk traverses all files in the folder (including files in the folder)

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

13. Get the absolute permission of files or folders in python program:

if os.path.exists(input_pathof_fileOrdir):

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

Tags: Python

Posted on Tue, 05 Nov 2019 11:12:02 -0800 by Azu