• 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)获得绝对路径,把路径和文件名拼接起来

  • 相关阅读:
    A49 - ESP8266建立AP传输XPT2046AD数据WIFI模块
    如何用Python做量化交易策略?
    Flask API 如何接入 i18n 实现国际化多语言
    一文带你了解容器技术的前世今生
    [附源码]JAVA毕业设计交通事故档案管理系统(系统+LW)
    好未来sre面经
    初步探索GraalVM——云原生时代JVM黑科技
    python folium 添加地图采样点及距离测量等属性
    做客户成功岗位有必要考PMP吗?
    扬帆起航:CCF开源发展论坛在深举办
  • 原文地址:https://blog.csdn.net/qq_52057693/article/details/126320360