python如何动态改变文件名
高洛峰
高洛峰 2016-10-26 14:18:37
[Python讨论组]

写一段python代码进行文件格式的转换,从.asc格式到 .pcd格式

#coding:utf-8
import time
from sys import argv
script ,filename = argv
print ("the input file name is:%r." %filename)

start = time.time()
print ("open the file...")
file = open(filename,"r+")
count = 0
#统计源文件的点数
for line in file:
    count=count+1
print ("size is %d" %count)
file.close()

output = open("out.pcd","w+")

list = ['# .PCD v.5 - Point Cloud Data file format\n','VERSION .5\n','FIELDS x y z\n','SIZE 4 4 4\n','TYPE F F F\n','COUNT 1 1 1\n']

output.writelines(list)
output.write('WIDTH ') #注意后边有空格
output.write(str(count))
output.write('\nHEIGHT')
output.write(str(1))  #强制类型转换,文件的输入只能是str格式
output.write('\nPOINTS ')
output.write(str(count))
output.write('\nDATA ascii\n')
file1 = open(filename,"r")
all = file1.read()
output.write(all)
output.close()
file1.close()

end = time.time()
print ("run time is: ", end-start)

这样只能输出特定的文件名out.pcd,请问如和改进脚本使得输出文件名与输入名名相同,后缀不同。例如:输入a.asc 自动输出a.pcd

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
三叔
#coding:utf-8
import time
from sys import argv
script ,filename = argv
print ("the input file name is:%r." %filename)

start = time.time()
print ("open the file...")
file = open(filename,"r+")
count = 0
#统计源文件的点数
for line in file:
    count=count+1
print ("size is %d" %count)
file.close()

f_prefix = filename.split('.')[0]
output_filename = '{prefix}.pcd'.format(prefix=f_prefix)
output = open(output_filename,"w+")

list = ['# .PCD v.5 - Point Cloud Data file format\n','VERSION .5\n','FIELDS x y z\n','SIZE 4 4 4\n','TYPE F F F\n','COUNT 1 1 1\n']

output.writelines(list)
output.write('WIDTH ') #注意后边有空格
output.write(str(count))
output.write('\nHEIGHT')
output.write(str(1))  #强制类型转换,文件的输入只能是str格式
output.write('\nPOINTS ')
output.write(str(count))
output.write('\nDATA ascii\n')
file1 = open(filename,"r")
all = file1.read()
output.write(all)
output.close()
file1.close()

end = time.time()
print ("run time is: ", end-start)

我在你代码里面修改了一些:

f_prefix = filename.split('.')[0]
output_filename = '{prefix}.pcd'.format(prefix=f_prefix)
output = open(output_filename,"w+")


热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号