Introduction to python os module

Keywords: PHP encoding Python

"""
rename file
    os.rename(src,dst)
    os.rename('123.txt','124.txt')
Delete files
    os.remove(path)
    os.remove('123.txt')
Create directory
    os.mkdir()
Create a multi-level directory
    os.makedirs()
Delete directory
    os.rmdir()
Delete multi level directory
    os.removedirs()
Get current directory
    os.getcwd()
Modify directory
    os.chdir()
Judge whether the file exists
    os.path.exists()
Determine whether it is a document
    os.path.isfile()
Determine whether it is a directory
    os.path.isdir()

Get absolute path
    os.path.abspath()
Determine whether it is an absolute path
    os.path.isabs()
Get the last part of the path
    os.path.basename()
Get parent path
    os.path.dirname()

Get subfolders in folder (important)
    os.listdir()

"""
import os
# os.rename("log.txt","log.properties")
# os.remove("log.properties")
# open("log.txt","w")
# os.mkdir("abc")
# os.rmdir("abc")
# os.makedirs("a/b/c/d")
# os.removedirs("a/b/c/d")
# os.chdir("../")
# print(os.getcwd())
# file_name = "abc.jpeg"
# if os.path.exists(file_name):
#     if os.path.isdir(file_name):
#print("delete folder succeeded")
#         os.rmdir(file_name)
#     elif os.path.isfile(file_name):
#print("delete file succeeded")
#         os.remove(file_name)
# else:
#print("file does not exist")

path = os.getcwd()

for f in os.listdir(path):
    if f.endswith(".py"):
        print(f)

Open this file with its default encoding

with open("your_file", 'rb') as fp:
    file_data = fp.read()
    result = chardet.detect(file_data)
    file_content = file_data.decode(encoding=result['encoding'])

Several cases

# 1. Encapsulate a function to write all the data in the Iterable object to the target file.
# If the string is not stored in Iterable, convert to string processing


def write_lines(file, Iterable):
    with open(file, mode="a", encoding="utf-8") as f:
        for i in Iterable:
            if isinstance(i, str):
                f.write(i + '\n')
            else:
                f.write(str(i) + "\n")


# write_lines("1.txt",[1,2,3,4,5,6,"abcde"])

  

# 2. Customize a function to copy the file (first read the target file, then write a new file)
# For example, def copyfile(file) copies a file. The name of the copied file is "file" copy. Suffix
def copyfile(file):
    filetup = file.rpartition(".")
    new_name = str(filetup[0]) + "_copy" + str(filetup[1] + filetup[2])
    if os.path.exists(file):
        with open(file, mode="r", encoding="utf-8") as f:
            with open(new_name, mode="w", encoding="utf-8") as f1:
                content = f.read(1024)
                while content:
                    f1.write(content)
                    content = f.read(1024)
    else:
        print("file not exists")


# copyfile("digui.py")

  

# 3. Print all file names in a folder
def print_all_file(file_path):
    file_list = os.listdir(file_path)
    for f in file_list:
        f = file_path + "\\" + f
        if os.path.isfile(f):
            print(f)
        elif os.path.isdir(f):
            print_all_file(f)


# print_all_file(r"E:\python workspace\day13")

  

# 4. Try to prefix all. py file names in a folder with your name (note that the file is backed up first)
# For example: test01.py - > XXX ﹣ test01.py
def add_prefix(file_path, prefix):
    file_list = os.listdir(file_path)
    for f in file_list:
        f = file_path + "\\" + f
        if os.path.isfile(f):
            basename = os.path.basename(f)
            dirname = os.path.dirname(f)
            # print(dirname+"\\"+prefix+basename)
            os.rename(f, dirname + "\\" + prefix + basename)
        elif os.path.isdir(f):
            add_prefix(f, prefix)


# add_prefix(r"E:\python workspace\day13","songdan_")

  

# 5. Encapsulate a function to realize the fuzzy query function similar to the operating system (input a keyword to show all files containing keywords in the target folder)
import chardet

def find_file_contains_key(f,key):
    if key in f:
        print(f"Contain{key}The file name of is:{f}:")
    with open(f, mode="rb") as fp:
        file_data = fp.read()
        result = chardet.detect(file_data)
        file_content = file_data.decode(encoding=result['encoding'])
        now_fname = ""
        for line in file_content:
            line = line.strip()
            if key in line:
                if now_fname == "":
                    now_fname = f.name
                    print(f"Contains{key}The file name of is:{f.name}:")

                print(f"\t\t The contents are:{line}")

def show_file_by_word(file_path, key):
    file_list = os.listdir(file_path)
    for f in file_list:
        f = file_path + "\\" + f
        # File, query whether there are keywords in it
        if os.path.isfile(f) and f.endswith(".py"):
            find_file_contains_key(f,key)
        # Folder, find the files inside
        elif os.path.isdir(f):
            show_file_by_word(f, key)

show_file_by_word(r"E:\python workspace\day13", "songdan")

  

# 6. Count the number of code lines in all. py files in a folder
count = 0
def count_file_words(file_path):
    file_list = os.listdir(file_path)
    global count
    for f in file_list:
        f = file_path + "\\" + f
        if os.path.isfile(f) and f.endswith(".py"):
            with open(f, mode="r", encoding="utf-8") as f:
                for line in f:
                    line = line.strip()
                    if "#" not in line and len(line) > 0:
                        count += 1

        # Folder, find the files inside
        elif os.path.isdir(f):
            count_file_words(f)

    return count

# count_file_words(r"E:\python workspace\day13\test")
print(count)

Posted by Pilli on Mon, 21 Oct 2019 10:22:53 -0700