我在一個名為 ( TU_1.ST01.XXX.TXT_,TU_1.ST02.XXX.TXT_, TU_1.ST03.XXX.TXT_, .......TU_1.ST1000.XXX.TXT_) 的目錄中有許多 .txt 檔案。我想并排排列所有文本檔案,并希望將其保存在一個檔案中,該檔案應該等于pasteshell 腳本中的命令。
任何人都可以幫我這樣做。
我試過腳本
import numpy as np
import os
import glob
for file in glob.glob("*.TXT_"):
print(file)
#here i want to arrange files
uj5u.com熱心網友回復:
示例輸入檔案:
$ 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
然后,您可以使用.to_csv()并設定sep是否要模擬選項卡式輸出paste
>>> print(df.T.to_csv(index=None, header=None, sep='\t'), end='')
one four six
two five seven
thee eight
nine
您也可以使用 itertools.zip_longest
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/420096.html
標籤:
上一篇:使用numpy向量化矩陣運算
