Common operations of files and files under python-1

Common operations of files and files under python:

1. List the contents of folders or files under the specified folder




import os



# print([x for x in os.listdir('.') if os.path.isdir(x)])


file1=os.listdir(r"d:\temp")

#  列出指定文件夹下文件夹的名称
for item in file1:
    # print(item)
    item="d:/temp/{}".format(item)
    if os.path.isdir(item):
        print(item)

# print(file1)

print("---------------")
# 列出指定文件夹下的文件内容
for itemfile in file1:
    itemfile="d:/temp/{}".format(itemfile)
    if os.path.isfile(itemfile):
        print(itemfile)

2. The directory location where your program runs:

print(os.getcwd())

3. What files are in the same level directory where your program is running

print(os.listdir(os.getcwd()))

4. Example: List the files in the directory under the specified path

file1=os.listdir(os.getcwd())

for itemfile in file1:
 
    if os.path.isfile(itemfile):
        print(itemfile)

5. Example: List the directory folders under the directory under the specified path

file1=os.listdir(os.getcwd())
for item in file1:

    if os.path.isdir(item):
        print(item)

6. Comprehensive

file1=os.listdir(os.getcwd())

for itemfile in file1:
    # itemfile = "d:/temp/{}".format(itemfile)
    if os.path.isfile(itemfile):
        print(itemfile)

for item in file1:
    # itemfile = "d:/temp/{}".format(itemfile)
    if os.path.isdir(item):
        print(item)

7. List derivation formula: In
this way, it can be realized in the current folder, but the path of the folder cannot be specified, and then test it again:

print([x for x in os.listdir('.') if os.path.isdir(x)])

The usage scenario is a program written by yourself, you can get the files and folders in the directory where the program is located.

[x for x in os.listdir('.') if os.path.isdir(x)]

Guess you like

Origin blog.csdn.net/wtt234/article/details/114122301