
path=r"D:\exp\resultdata" //文件夹途径
for (root, dirs, files) in os.walk(path):
os.walk(path)//遍历D:\exp\resultdata下文件
(二)获得新文件名(如何打开一个文件)
一般新文件名都保存在一个文件中
new_names_files=open('文件名.txt','r')
content=open('文件名.txt','r')(此时content是一个含有所有new name 的列表)
注意:对新名字(字符串)会有一些 *** 作
(1)对文件名(字符)的分割
用split()进行分割
a=''wer.werrew/"
(2)list 添加新的元素、
用append()进行添加
(3)字典添加新的元素
用update()进行添加
实例:
(三)重命名
利用os.rename()函数
实例:旧名字与新名字的数字相对
file=['1.max','2.max'……]//旧名字
for file in files:
oldname = os.path.join(root,file)
namesp=file.split('.')
new_namesp=d[int(namesp[0])]//数字相对
newname = os.path.join(root,new_namesp)
os.rename(oldname,newname)
不清楚你的实际文件/情况,仅以问题中的样例/说明及猜测为据;以下代码复制粘贴到记事本,另存为xx.py
# encoding: utf-8# Python 3.9.6
import os
import sys
srcfile='./文件名.txt'
dstfolder='D:/ZLSJ'
if not os.path.exists(srcfile):
print('"%s" does not exist' % srcfile)
sys.exit()
if not os.path.exists(dstfolder):
print('"%s" does not exist' % dstfolder)
sys.exit()
f=open(srcfile, encoding='utf-8')
content=f.readlines()
f.close()
file_list=[]
for file in os.listdir(dstfolder):
if file.lower().endswith('.txt'):
file_list.append(file)
n=0
#如果原文件名全部以纯数字命名,则对原文件升序排列
file_list.sort(key=lambda e:int(e[0:-4]))
for file in file_list:
if n < len(content):
newname=content[n].strip()
oldfile=os.path.join(dstfolder, file)
newfile=os.path.join(dstfolder, newname)
print('{0} --> {1}'.format(oldfile, newname))
os.rename(oldfile, newfile)
n=n+1
用+号连接符连接后缀名ouput=open(str1+".txt",'w')//,用引号括起来表示的是字符串常量,不在引号中才表示变量,//,是在windows下运行,变量str1中不能有在文件名中不能出现的特殊字符。
in.close()如果你仅仅想知道如何连接string,file_a = "{date}。
{ext}".format(date=f, ext="txt")file_b = "{date}.{ext}".format(date=f, ext="jpg")。
扩展资料:
Python在执行时,首先会将.py文件中的源代码编译成Python的byte code(字节码),然后再由Python Virtual Machine(Python虚拟机)来执行这些编译好的byte code。这种机制的基本思想跟Java,.NET是一致的。
这里的高级并不是通常意义上的高级,不是说Python的Virtual Machine比Java或.NET的功能更强大,而是说和Java 或.NET相比,Python的Virtual Machine距离真实机器的距离更远。
除此之外,Python还可以以交互模式运行,比如主流 *** 作系统Unix/Linux、Mac、Windows都可以直接在命令模式下直接运行Python交互环境。直接下达 *** 作指令即可实现交互 *** 作。
参考资料来源:百度百科-Python
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)