python文件和文件夹的相关操作

1. 文件io

def read_file():
    with open("a.txt") as file:
        var = file.readlines()
        for str in var:
            print(str, end="")
    file.close()

格式打印

print ("我叫 %s 今年 %d 岁!" % ('小明', 10))


print('{0} is {1}'.format('hha', 'z'))
print('{0} 和 {1}'.format('Google', 'fffff'))

test_thress_quo = """ 
所见
即
所得
"""
print(test_thress_quo)

# 遍历器
list=[1,2,3,4]
it = iter(list)
for tmp in it:
    print('这里就是数据: ',tmp, end="\n \n")

2. 本地文件管理

遍历文件夹,文件


import os


# 巡视路径下的 文件夹 文件
def folder_function(path):
    for root, dirs, files in os.walk(path):
        # 当前父路径
        print(root, end="++++root \n")
        print("-------------------------")
        print(dirs, end="文件夹\n")
        print("-------------------------")
        print(files, end="文件 \n")

文件后缀分类

# 文件名称后后缀分离
def folder_function_2(path):
    for root, dirs, files in os.walk(path):
        for file in files:
            file_name, ending = os.path.splitext(file)
            if(ending == '.py'):
                print("file name is ", file_name, "      ---ending is ", ending)


存入list

def listdir(path, list_name):  #传入存储的list
    for file in os.listdir(path):
        file_path = os.path.join(path, file)
        if os.path.isdir(file_path):
            listdir(file_path, list_name)
        else:
            list_name.append(file_path)

    print(list_name)
```**加粗样式**

你可能感兴趣的:(#,Python)