读写文件
# ! /usr/bin/python
# -*- coding: utf8 -*-
spath = " D:/download/baa.txt "
f = open(spath, " w " ) # Opens file for writing.Creates this file doesn't exist.
f.write( " First line 1.\n " )
f.writelines( " First line 2. " )
f.close()
f = open(spath, " r " ) # Opens file for reading
for line in f:
print ( " 每一行的数据是:%s " % line)
f.close()
'''
知识点: 如何读写文件
'''
遍历文件夹和文件
import os
import os.path
# os,os.path里包含大多数文件访问的函数,所以要先引入它们.
# 请按照你的实际情况修改这个路径
rootdir = " d:/download "
for parent, dirnames, filenames in os.walk(rootdir):
# case 1:
for dirname in dirnames:
print ( " parent is: " + parent)
print ( " dirname is: " + dirname)
# case 2
for filename in filenames:
print ( " parent is: " + parent)
print ( " filename with full path : " + os.path.join(parent, filename))
''' 知识点:
* os.walk返回一个三元组.其中dirnames是所有文件夹名字(不包含路径),filenames是所有文件的名字(不包含路径).parent表示父目录.
* case1 演示了如何遍历所有目录.
* case2 演示了如何遍历所有文件.
* os.path.join(dirname,filename) : 将形如"/a/b/c"和"d.java"变成/a/b/c/d.java".
'''
分割路径和文件名
import os.path
# 常用函数有三种:分隔路径,找出文件名.找出盘符(windows系统),找出文件的扩展名.
# 根据你机器的实际情况修改下面参数.
spath = " D:/download/repository.7z "
# case 1:
p,f = os.path.split(spath);
print ( " dir is: " + p)
print ( " file is: " + f)
# case 2:
drv,left = os.path.splitdrive(spath);
print ( " driver is: " + drv)
print ( " left is: " + left)
# case 3:
f,ext = os.path.splitext(spath);
print ( " f is: " + f)
print ( " ext is: " + ext)
'''
知识点: 这三个函数都返回二元组.
* case1 分隔目录和文件名
* case2 分隔盘符和文件名
* case3 分隔文件和扩展名
'''
总结:5个函数
- os.walk(spath)
- os.path.split(spath)
- os.path.splitdrive(spath)
- os.path.splitext(spath)
- os.path.join(path1,path2)
复制文件
import shutil
import os
import os.path
src = " d:\\download\\test\\myfile1.txt "
dst = " d:\\download\\test\\myfile2.txt "
dst2 = " d:/download/test/测试文件夹.txt "
dir1 = os.path.dirname(src)
print ( " dir1 %s " % dir1)
if (os.path.exists(src) == False):
os.makedirs(dir1)
f1 = open(src, " w " )
f1.write( " line a\n " )
f1.write( " line b\n " )
f1.close()
shutil.copyfile(src, dst)
shutil.copyfile(src, dst2)
f2 = open(dst, " r " )
for line in f2:
print (line)
f2.close()
# 测试复制文件夹树
try :
srcDir = " d:/download/test "
dstDir = " d:/download/test2 "
# 如果dstDir已经存在,那么shutil.copytree方法会报错!
# 这也意味着你不能直接用d:作为目标路径.
shutil.copytree(srcDir, dstDir)
except Exception as err:
print (err)
'''
知识点:
* shutil.copyfile:如何复制文件
* os.path.exists:如何判断文件夹是否存在
* shutil.copytree:如何复制目录树
'''
总结:4个函数
- os.path.dirname(path)
- os.path.exists(path)
- shutil.copyfile(src, dst)
- shutil.copytree(srcDir, dstDir)
实战:文件备份小程序
import os
import shutil
import datetime
'''
作用:将目录备份到其他路径。
实际效果:
假设给定目录"/media/data/programmer/project/python" ,
备份路径"/home/diegoyun/backup/“ ,
则会将python目录备份到备份路径下,形如:
/home/diegoyun/backup/yyyymmddHHMMSS/python/xxx/yyy/zzz..
用法:更改这两个参数.
backdir:备份目的地.
copydirs:想要备份的文件夹.
'''
def mainLogic():
# add dirs you want to copy
backdir = " d:\\test "
print (backdir)
copydirs = []
copydirs.append( " d:\\temp " );
# copydirs.append("d:\\test");
print ( " Copying files =================== " )
start = datetime.datetime.now()
# gen a data folder for backup
backdir = os.path.join(backdir,start.strftime( " %Y-%m-%d " ))
# print("backdir is:"+backdir)
kc = 0
for d in copydirs:
kc = kc + copyFiles(d,backdir)
end = datetime.datetime.now()
print ( " Finished! =================== " )
print ( " Total files : " + str(kc) )
print ( " Elapsed time : " + str((end - start).seconds) + " seconds " )
def copyFiles(copydir,backdir):
prefix = getPathPrefix(copydir)
# print("prefix is:"+prefix )
i = 0
for dirpath,dirnames,filenames in os.walk(copydir):
for name in filenames:
oldpath = os.path.join(dirpath,name)
newpath = omitPrefix(dirpath,prefix)
print ( " backdir is: " + backdir )
newpath = os.path.join(backdir,newpath)
print ( " newpath is: " + newpath)
if os.path.exists(newpath) != True:
os.makedirs(newpath)
newpath = os.path.join(newpath,name)
print ( " From: " + oldpath + " to: " + newpath)
shutil.copyfile(oldpath,newpath)
i = i + 1
return i
def getPathPrefix(fullpath):
# Giving /media/data/programmer/project/ , get the prefix
# /media/data/programmer/
l = fullpath.split(os.path.sep)
# print(str(l[-1]=="")
if l[ - 1 ] == "" :
tmp = l[ - 2 ]
else :
tmp = l[ - 1 ]
return fullpath[0:len(fullpath) - len(tmp) - 1 ]
def omitPrefix(fullpath,prefix):
# Giving /media/data/programmer/project/python/tutotial/file/test.py ,
# and prefix is Giving /media/data/programmer/project/,
# return path as python/tutotial/file/test.py
return fullpath[len(prefix) + 1 :]
mainLogic()
分享到:
相关推荐
python遍历文件夹和文件 这个也许是最常用的功能,如下: 复制代码 代码如下:import os import os.path rootdir = “D:\\programmer\\training” for parent, dirnames, filenames in os.walk(rootdir):...
本文实例为大家分享了python的ini配置文件操作工具类的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*- @Time : 2018/6/22 @Author : LiuXueWen @Site : @File : Util_Ini...
# -*- coding: utf-8 -*- # @Time : 2019-11-18 09:31 # @Author : cxa # @File : toml_demo.py ...class FileOperation: def __init__(self): self.dic = dict() self.toml_file_path = os.path.join(BASE_DIR,
Navigating the File System with the os Module 178 Try It Out: Listing Files and Playing with Paths 180 Try It Out: Searching for Files of a Particular Type 181 Try It Out: Refining a Search 183 ...
Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...
二、FileRead:获取招生数据过程中的文件读取 1、py文件 (1)、FileNameRead.py(读取文件名) (2)、ImageRead.py(读取图片) (3)、PDFRead.py(读取PDF(表格、文字)) (4)、XLSRead.py(读取excel表格) 三、HanLP:中文自然...
matlab简单图像处理代码Python图像处理OpenCV教学示例 OpenCV Python图像处理示例,用于在位于英国(英国)的计算机科学专业课程中进行教学。 所有版本均通过3.x / 4.x和Python 3.x进行了测试。 # Example : <......
conda env create --file environment.yaml用法将作业提交到Slurm调度程序: sbatch job.sh常见问题非法反射访问操作使用Java版本> = 9加载Spark时,将显示警告。 WARNING: An illegal reflective access operation...
util—operation_excel:操作excel #-*-encoding:utf-8-*- import xlrd from xlutils.copy import copy import os dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class OperationExcel(): ''' ...
Setcmp 对项目清单执行设置操作安装$ python setup.py install用法usage: setcmp [-h] left op rightPerform set operation on list of items.positional arguments: left Base csv file containing one item per ...
shell-init: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory 该错误表示 getcwd 命令无法定位到当前工作目录。一般来说是因为你 cd 到了某个目录之后 ...
将文件上传到S3: import botocore . session session = botocore . session . get_session () s3 = session . get_service ( 's3' ) endpoint = s3 . get_endpoint ( region ) fp = open ( './testfile.txt' , '...
1:安装命令 pip install docker-compose 异常信息 socket.timeout: The read operation ...File “/usr/local/lib/python3.6/site-packages/pip/_internal/cli/base_command.py”, line 188, in _main status = se
数据科学培训 这是数据科学的火车 技能图 斜体是python库 1.基本技能 打字 Python SQL 2.基础设施 - Terminal - iterm - WindowsTerminal - HomeBrew - Linux ...- FileOperation - *pathlib* - *
点击右边Links(链接)中的Encode(编译),界面最下面的Console(控制台)窗口显示“The operation has completed successfully.”,意思为编译已经完成。 现在再去加密后文件保存的目录中,会看到其中也有一个...
批量查找和替换多个Git存储库中的多个文件该脚本的使用区域当您要批量更改多... 在repository_list中添加新的分支名称和存储库添加文本以查找和替换find_and_replace_list 添加文件以检入file_list 更改提交消息commit_
用于处理OS X和iOS沙箱配置文件的各种工具 到目前为止,以下工具已开源: compile_sb - a sandbox script to binary compiler for iOS and OS X extract_sbops - a sandbox operation names extractor for iOS ...
For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having ...
Contents About the Author...............................................................................................xix About the Technical Reviewer and Contributing Author.................xxi ...