【问题标题】:Copy only one column from many text files and create a single new file with tab separated new columns using Python or Bash仅从多个文本文件中复制一列,并使用 Python 或 Bash 创建一个带有制表符分隔的新列的新文件
【发布时间】:2013-03-28 15:34:07
【问题描述】:

我有很多文件,每个文件都有以下结构:

文件一:

1 x
2 r
3 f
4 t
: :
: :
1000 k

第二个文件:

1 x
2 r
3 f
4 t
: :
: :
1000 k

有数百个这样的文件。 我需要一个最终输出文件作为每个文件的制表符分隔的第二列

输出文件:

x ..More Columns ... q
r ..... w
f ..... e
t ..... l
:       :
:       :

我更喜欢使用 Python 或 Bash 脚本。 抱歉这个愚蠢的问题。

这是我到目前为止的进展,为每个文件的第二列创建了一个 * 分隔字符串列表。 但是没有产生如何编写它们的想法 代码:

import tkinter.filedialog
def FileToString (fin):
    Result = ''
    for line in fin:
        LineList = line.strip().split(' ')
        Result = Result + '*' + LineList[1]
return (Result)


File = tkinter.filedialog.askopenfilenames(title='Select the Files you want>> >>> >> >>>>')
Filenames = File.split()
Result = []
ArrayResult = []
OutPutFileName = tkinter.filedialog.asksaveasfilename(title='Select or Enter Output File >>     >>>> >>>>')
fout = open(OutPutFileName,'w')
for name in Filenames:
    fin = open(name,'r')
    FileResult = FileToString(fin)
    ArrayResult.append(FileResult)

谢谢

【问题讨论】:

  • 试试csv模块docs.python.org/2/library/csv.html当你卡住时回来;)
  • 到目前为止你写了什么?
  • @p.in4matics 虽然这是一个有效的问题,但你被否决了,因为它没有显示任何研究工作的努力
  • @RandyHoward 我粘贴了上面的代码。

标签: python bash python-3.x sed awk


【解决方案1】:

在命令行...

paste file1 file2 > file3

这是我的来源:Lesser-known Linux commands: join, paste, and sort

如果这不是您要找的内容,请回复,我会努力解决的。


试试这个...把“file*”和“out.txt”改成你需要的样子。

#!/bin/sh
outFile=out.txt
tmpFile=$$.tmp
for FILE in `ls file*`
do
    if [ ! -f ${tmpFile} ]; then
        # Need to seed the tmp file one first pass
        cp ${FILE} ${tmpFile}
        continue
    fi
    paste ${tmpFile} ${FILE} > ${outFile}
    mv ${outFile} ${tmpFile}
done
# Move the tmp file to output file
mv ${tmpFile} ${outFile}

【讨论】:

  • 谢谢,但是如果我有过多的文件怎么办。
  • 即使文件中的行数不同,似乎也可以工作。
【解决方案2】:
awk '
{ a[FNR] = a[FNR] (NR==FNR?"":"\t") $2 }
END{ for (i=1;i<=FNR;i++) print a[i] }
' file1 file2 file3 ....

【讨论】:

    猜你喜欢
    • 2016-01-05
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多