优雅的文件组合方式 – Python
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了优雅的文件组合方式 – Python,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2659字,纯文字阅读大概需要4分钟。
内容图文
嗨只是一个简单的问题.我有一个完美无缺的文件串联,但它有点混乱.我想知道是否只有更优雅的方式来写这个:
path = path/to/file/location
with open(path + 'result.txt', 'w') as result, open(path + 'file1.txt') as f1, open(path + 'file2.txt' ) as f2, open(path + 'file3.txt' ) as f3, open(path + 'file4.txt' ) as f4, open(path + 'file5.txt' ) as f5, open(path + 'file6.txt' ) as f6, open(path + 'file7.txt' ) as f7, open(path + 'file8.txt' ) as f8, open(path + 'file9.txt' ) as f9, open(path + 'file10.txt' ) as f10, open(path + 'file11.txt' ) as f11, open(path + 'file12.txt' ) as f12, open(path + 'file13.txt' ) as f13, open(path + 'file14.txt' ) as f14, open(path + 'file15.txt' ) as f15, open(path + 'file16.txt' ) as f16:
for line1, line2, line3, line4, line5, line6, line7, line8, \
line9, line10, line11, line12, line13, line14, line15, line16 in zip(f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16):
result.write('{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}\n'.format(line1.rstrip(), line2.rstrip(), line3.rstrip(), line4.rstrip(), line5.rstrip(), line6.rstrip(), line7.rstrip(), line8.rstrip(), line9.rstrip(), line10.rstrip(), line11.rstrip(), line12.rstrip(), line13.rstrip(), line14.rstrip(), line15.rstrip(), line16.rstrip()))
谢谢
解决方法:
您可以随时执行此操作,将文件放在列表中并在一切完成后手动关闭它们.这也将使格式行更简单:
path = "path/to/file/location/"
with open(path + 'result.txt', 'w') as result:
files = [open(path + 'file%d.txt' % (n+1)) for n in range(16)]
form = ", ".join('{}' for f in files) + '\n'
for lines in zip(*files):
result.write(form.format(*map(str.rstrip, lines)))
for f in files:
f.close()
或者使用contextlib.ExitStack,如评论中所示.这样,打开的文件将传递给堆栈,并将在with块之后关闭文件.
with open(path + 'result.txt', 'w') as result, contextlib.ExitStack() as stack:
files = [stack.enter_context(open(path + 'file%d.txt' % (n+1))) for n in range(16)]
form = ", ".join('{}' for f in files) + '\n'
for lines in zip(*files):
result.write(form.format(*map(str.rstrip, lines)))
内容总结
以上是互联网集市为您收集整理的优雅的文件组合方式 – Python全部内容,希望文章能够帮你解决优雅的文件组合方式 – Python所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。
来源:【匿名】