【发布时间】:2013-12-28 12:26:19
【问题描述】:
我有一组文本文件,我希望将每个文本文件的第二列按顺序添加到一个新的文本文件中。这些文件是制表符分隔的,格式如下:
name dave
age 35
job teacher
income 30000
我已经生成了一个文件,其中一个文件的第一列代替了第二列,希望能简化问题:
0 name
0 age
0 job
0 income
我有大量这些文件,并希望将它们全部放在制表符分隔的文本文件中,例如:
name dave mike sue
age 35 28 40
job teacher postman solicitor
income 30000 20000 40000
我有一个文本文件,其中只包含名为 all_libs.txt 的所有文件的名称
到目前为止,我已经写了:
#make a sorted list of the file names
with open('all_libs.txt', 'r') as lib:
people = list([line.rstrip() for line in lib])
people_s = sorted(people)
i=0
while i< len(people_s):
with open(people_s[i]) as inf:
for line in inf:
parts = line.split() #split line into parts
if len(parts) > 1: #if more than 1 discrete unit in parts
with open("all_data.txt", 'a') as out_file: #append column2 to all_data
out_file.write((parts[1])+"\n")
i=i+1 #go to the next file in the list
在打开每个新文件时,我想将其添加为新列,而不是仅作为新行追加。真的很感激任何帮助吗?我意识到像 SQL 这样的东西可能会让这变得简单,但我从未使用过它,也没有时间致力于 SQL 的学习曲线。非常感谢。
【问题讨论】:
标签: python text multiple-columns