【问题标题】:arranging files in a text file在文本文件中排列文件
【发布时间】:2022-01-22 17:39:21
【问题描述】:

我在一个名为 (TU_1.ST01.XXX.TXT_,TU_1.ST02.XXX.TXT_, TU_1.ST03.XXX.TXT_, .......TU_1.ST1000.XXX.TXT_) 的目录中有许多 .txt 文件。我想将所有文本文件并排排列,并希望将其保存在一个文件中,该文件应等于 shell 脚本中的paste 命令。

谁能帮我做这件事。

我试过脚本

import numpy as np
import os
import glob

for file in glob.glob("*.TXT_"):
    print(file)
    #here i want to arrange files 

【问题讨论】:

  • 您的意思是..复制目录中的所有 *.TXT 文件?什么是并排?
  • 将 .TXT 文件粘贴到文件中
  • 我认为这可以使用 numpy.zip @PySaad 来完成
  • 推荐shutil包。要复制和过去的目录,shutil.copytree("source dir", "destination dir")

标签: python pandas numpy glob


【解决方案1】:

示例输入文件:

$ paste *.txt
one    four    six
two    five    seven
thee           eight   
               nine

使用pandas 是一种选择。

import pandas  as pd
from   pathlib import Path

>>> pd.DataFrame(f.read_text().splitlines() for f in Path().glob('*.txt'))
      0      1      2     3
0   one    two   thee  None
1  four   five   None  None
2   six  seven  eight  nine

然后您可以.tranpose() / .T 将每个文件变成自己的列。

>>> df = pd.DataFrame(f.read_text().splitlines() for f in Path().glob('*.txt'))
>>> df.T
      0     1      2
0   one  four    six
1   two  five  seven
2  thee  None  eight
3  None  None   nine

如果您想模拟来自paste 的选项卡式输出,您可以使用.to_csv() 并设置sep

>>> print(df.T.to_csv(index=None, header=None, sep='\t'), end='')
one    four    six
two    five    seven
thee           eight   
               nine

你也可以使用itertools.zip_longest实现它

【讨论】:

  • 如何将其保存到带有制表符分隔的 ascii 文件中
  • 您能否建议如何使用 itertools.zip_longest 获取更多文件
猜你喜欢
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2016-04-18
  • 2023-04-03
  • 2016-05-16
  • 2016-08-02
相关资源
最近更新 更多