• Python输入输出、遍历文件夹(input、stdin、os.path)


    目录

    1. 输入 input()、sys.stdin.readline()

    2. 输出 print()

    3. 遍历文件夹 os.walk()、os.path.xxx()


    1. 输入

    input 交互式输入

    1. # 读入一个数字
    2. n = int(input())
    3. # 读入两个或以上数字
    4. m, n = map(int, input().split())
    5. # 一行数据,以空格分隔
    6. line = input()
    7. arr = []
    8. for i in line.split():
    9. arr.append(int(i))

    sys.stdin.readline() 标准输入

    1. import sys
    2. # 一行一行读取 并分隔为列表
    3. line = sys.stdin.readline().split()
    4. # 取出n值
    5. n = int(line[0])

    读入矩阵(input循环)

    1. # 读入矩阵(多行),以空格分隔
    2. arr = []
    3. while 1:
    4. s = input()
    5. if s != "":
    6. arr.append(list(map(int, s.split())))
    7. else:
    8. break
    9. # 读入矩阵(多行),输入的数组中带有中括号和逗号
    10. arr = []
    11. while 1:
    12. s = input()
    13. if s != "":
    14. arr.append(list(map(int, s.replace("],", "").replace(" ", "").replace("[", "").replace("]", "").split(","))))
    15. else:
    16. break

    2. 输出

    输出列表,以空格分隔:

    1. # 输出列表,以空格分隔
    2. for i in arr:
    3. print(i,end=" ")
    4. # 输出列表,以空格分隔(严格版)
    5. for i in range(n):
    6. if i != n-1:
    7. print(ret[i],end=" ")
    8. else:
    9. print(ret[i])

    3. 遍历文件夹

    os.walk()自动递归找出所有文件名

    1. for filepath,dirnames,filenames in os.walk(r'xxxxx'):
    2. for filename in filenames:
    3. print (os.path.join(filepath,filename))

    遍历文件夹下的所有文件,获取文件名列表

    1. import os
    2. def allfiles(path, all_files=[]):
    3. # 当输入路径存在时才获取路径下文件列表
    4. if os.path.exists(path):
    5. files = os.listdir(path)
    6. # 遍历files列表
    7. for file in files:
    8. # 判断是否为文件夹
    9. if os.path.isdir(os.path.join(path, file)):
    10. # 递归调用
    11. allfiles(os.path.join(path, file),all_files)
    12. else:
    13. all_files.append(os.path.join(path, file))
    14. return all_files

    获取路径下包含指定名字的文件路径(path指定路径,name要找的文件名)

    1. import os
    2. def allfiles(path, name, all_files=[]):
    3. # 当输入路径存在时才获取路径下文件列表
    4. if os.path.exists(path):
    5. files = os.listdir(path)
    6. # 遍历files列表
    7. for file in files:
    8. # 判断是否为文件夹
    9. if os.path.isdir(os.path.join(path, file)):
    10. # 递归调用
    11. allfiles(os.path.join(path, file), name, all_files)
    12. else:
    13. if name in file:
    14. all_files.append(os.path.join(path, file))
    15. return all_files

    常用os方法

    os.walk(folder)返回 filepath,dirnames,filenames三元组
    os.path.exists(path)判断路径是否存在
    os.path.isdir(xxx)判断是否为路径
    os.path.isfile(xxx)判断是否为文件
    os.listdir(path)返回路径下所有文件夹和文件名
    os.getcwd()获得当前执行路径
    os.path.join(path, name)获得绝对路径,把路径和文件名拼接起来

  • 相关阅读:
    以太坊是什么? 以及以太坊如何工作的?
    golang roadrunner中文文档(一)基础介绍
    mall :rabbit项目源码解析
    数据结构题目收录(十九)
    如何一次性解压多个文件
    Zookeeper高级_四字命令
    必应bing国内广告怎样开户投放呢?
    MySQL中SQL语句的执行顺序
    【一起学Rust】Rust的Hello Rust详细解析
    Qt学习04 Hello Qt
  • 原文地址:https://blog.csdn.net/qq_52057693/article/details/126320360