File operation based on OS module in Python

Keywords: Linux Windows Python

1, Operation of OS module on files

1. Returns the operating system type (posix is the linux operating system, nt is the windows operating system)

important os
print os.name

2. Return operating system details

import os
print os.uname()

3. Environment variables of the system

import os
print os.environ
print os.environ.get('PATH')

4. Determine whether it is an absolute path (does not determine whether a file or directory exists)

import os
print os.path.isabs('/tmp/westos')
print os.path.isabs('hello')

Starting with the root is the absolute path

5. Generate absolute path (two methods generate absolute path of current environment)

import os
#The first method
print os.path.abspath('han.png')    #Absolute path to the current environment
print os.path.join('/home/kiosk','han.png')    #The absolute path to the "han.png" file starting with / home/kiosk
#The second method
print os.path.join(os.path.abspath('.'),'han.png') 

6. Get directory name or file name

import os
filename ='/home/kiosk/PycharmProjects/python/day08 Own/hello.png'
print os.path.basename(filename)
print os.path.dirname(filename)

7. Create directory / delete directory

import os
os.mkdir('dir')
os.makedirs('text/file')

os.rmdir('img')    #Only existing directories can be deleted, and the deleted directory can only be deleted one level. It cannot be deleted together with the files under the directory

8. Create / delete files

import os
os.mknod('westos.txt')
os.remove('westos.txt')

9. Rename of file

import os
os.rename('westos.txt','date.txt')    #Rename westos.txt to date.txt

10. Determine whether the file or directory exists

import os
print os.path.exists('img')       
print os.path.exists('westos.txt')

11. Separating suffix and filename

import os
print os.path.splitext('hello.png')  

12. Separate directory and filename

import os
print os.path.split('/tmp/hello/hello.png')

2, Case study

Demand:

  1. Create a new directory img in the current directory, which contains multiple files with different file names (X4G5.png)
  2. Change all suffixes ending with. png in the current img directory to. jpg
import os
import random
import string
def gen_code(len=4):
    # Randomly generate 4-bit file name
    li = random.sample(string.ascii_letters + string.digits, len)
    # Concatenate list elements into strings
    return ''.join(li)
def create_file():
    # Randomly generate multiple file names
    li = {gen_code() for i in range(100)}
    os.mkdir('img')
    for name in li:
        os.mknod('img/' + name + '.png')
def modify_suffix(dirname, old_suffix, new_suffix):
    """
    :param dirname:  Directory to operate on
    :param old_suffix: Previous file suffix
    :param new_suffix: New file suffix
    :return:
    """
    # 1. Judge whether the directory to be searched exists. If not, an error will be displayed
    if os.path.exists(dirname):
        # 2. Find all files ending in old_suffix(.png)
        pngfiles = [filename for filename in os.listdir(dirname)
                    if filename.endswith(old_suffix)]
        # 3. Separate the file name and suffix name, and leave the file name
        basefiles = [os.path.splitext(filename)[0] for filename in pngfiles]
        print basefiles
        # 4. Text rename
        for filename in basefiles:
            # Directory name required
            oldname = os.path.join(dirname, filename + old_suffix)
            newname = os.path.join(dirname, filename + new_suffix)
            os.rename(oldname, newname)
            print '%s Rename as%s Success' % (oldname, newname)
    else:
        print '%s No operation....' % dirname
modify_suffix('img','.jpg','.png')

 

 

 

 

Posted by habanero25 on Sun, 29 Dec 2019 07:43:36 -0800