首页 > 编程语言 > 详细

【Py】Python的调包日常——文件操作篇

时间:2020-06-16 22:05:13      阅读:74      评论:0      收藏:0      [点我收藏+]

遍历一个文件夹下所有文件(文件夹可以嵌套)

import os 

basepath = ‘./‘

def get_file_from_path(path):
      if os.path.isdir(path):
            # 处理这个文件夹
            for item in os.listdir(path):
                  next_path=os.path.join(path, item)
                  get_file_from_path(next_path)
            print("All item in dir_path", next_path, " has been processed")
      else:
            # 处理这个文件

复制文件

from shutil import copyfile

copyfile(frompath,topath)

写文件

fp = open(filepath, ‘a‘)
fp.write(stringtowrite)
fp.close()

读文件

fp = open(filepath, ‘r‘)
lines=fp.readlines()
for line in lines:
      #处理每一行
fp.close()

新建文件夹

if not os.path.exists(dir_path):
      os.mkdir(dir_path) #存在会报错

【Py】Python的调包日常——文件操作篇

原文:https://www.cnblogs.com/Ryan16231112/p/13144445.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!