从Python中复制多个文本文件中的列
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了从Python中复制多个文本文件中的列,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1810字,纯文字阅读大概需要3分钟。
内容图文
![从Python中复制多个文本文件中的列](/upload/InfoBanner/zyjiaocheng/792/0a36a6548e88447c9069faa38e026c0e.jpg)
我有大量的文本文件包含排列成固定数量的行和列的数据,列由空格分隔. (像.csv一样,但使用空格作为分隔符).我想从每个文件中提取一个给定的列,并将其写入一个新的文本文件.
到目前为止,我尝试过:
results_combined = open('ResultsCombined.txt', 'wb')
def combine_results():
for num in range(2,10):
f = open("result_0."+str(num)+"_.txt", 'rb') # all the text files have similar filename styles
lines = f.readlines() # read in the data
no_lines = len(lines) # get the number of lines
for i in range (0,no_lines):
column = lines[i].strip().split(" ")
results_combined.write(column[5] + " " + '\r\n')
f.close()
if __name__ == "__main__":
combine_results()
这将生成一个文本文件,其中包含我想要的单独文件中的数据,但是作为单个列. (即我已经设法将列堆叠在一起,而不是将它们作为单独的列并排放置).我觉得我错过了一些明显的东西.
在另一次尝试中,我设法将所有单独的文件写入单个文件,但没有选择我想要的列.
import glob
files = [open(f) for f in glob.glob("result_*.txt")]
fout = open ("ResultsCombined.txt", 'wb')
for row in range(0,488):
for f in files:
fout.write( f.readline().strip() )
fout.write(' ')
fout.write('\n')
fout.close()
我基本上想要的是从每个文件中复制第5列(它始终是同一列)并将它们全部写入单个文件.
解决方法:
如果您不知道文件中的最大行数以及文件是否适合内存,那么以下解决方案将起作用:
import glob
files = [open(f) for f in glob.glob("*.txt")]
# Given file, Read the 6th column in each line
def readcol5(f):
return [line.split(' ')[5] for line in f]
filecols = [ readcol5(f) for f in files ]
maxrows = len(max(filecols, key=len))
# Given array, make sure it has maxrows number of elements.
def extendmin(arr):
diff = maxrows - len(arr)
arr.extend([''] * diff)
return arr
filecols = map(extendmin, filecols)
lines = zip(*filecols)
lines = map(lambda x: ','.join(x), lines)
lines = '\n'.join(lines)
fout = open('output.csv', 'wb')
fout.write(lines)
fout.close()
内容总结
以上是互联网集市为您收集整理的从Python中复制多个文本文件中的列全部内容,希望文章能够帮你解决从Python中复制多个文本文件中的列所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。