Basic exercises of python module os

Table of contents

Topic: Get the content of the current directory, just print it

What needs to be used

resolve code


Topic: Get the content of the current directory, just print it

"""
# print all contents of a directory
# Primary resolution content
# Judgment: If it is a directory, after the printing is completed, you need to enter the directory and then print.
# If it is a file, print it directly
# 1 How to determine whether it is a file or a directory
# 2 How to enter a directory
# 3 Solve the path problem
# In the os model there are
"""

What needs to be used

# os.listdir(file path (path)) List the content in the current directory
# Note: "\t" is a tab character, and "\" is an escape character, you can use "\" to escape "\ t", such as "\\t".
# os.path.isfile (file path (path)) to determine whether it is a file
# os.path.isdir (file path (path)) to determine whether it is a directory
# os.chdir() change directory change directory (enter other working directory)
# os.getcwd() Get the current working directory
# os.path.join() Join path

import os

print(os.listdir("D:\\text"))   # 内容有['text.txt', 'text2']
print(os.path.isfile("D:\\text"))  # 是否为文件False
print(os.path.isdir("D:\\text"))   # 是否为目录True
print(os.getcwd())  # 此文件路径D:\python_code\homework\modle_homework
print(os.path.join("D:\\text", "text2"))  # 拼接结果D:\text\text2

resolve code

import os


def print_directory(path, level=1):
    for file_name in os.listdir(path):
        if os.path.isfile(os.path.join(path, file_name)):
            print("\t" * level + file_name)
        if os.path.isdir(os.path.join(path, file_name)):
            print("\t" * level + file_name)
            print_directory(os.path.join(path, file_name), level + 1)


print_directory("D:\\text")
# 内容呈现
'''
	text.txt
	text2
		text2.txt
		text3
			text3.txt
			text4
				text4.txt
'''

 

Guess you like

Origin blog.csdn.net/2302_77035737/article/details/130669037