[英]arranging files side by side
我在一个目录中有文本文件(file1,file2,file3 ...),我想根据文件名进行排序,并将文件并排排列在一个单独的文本文件中。
cat file1 cat file2 cat file3
1 4 8
3 5 1
4 6 3
预计 output
cat output.txt
1 4 8
3 5 1
4 6 3
我的代码:
import glob
myfiles = glob.glob('file*')
for file in myfiles:
#from here i cannot proceed
您可以按其中的 integer 对文件列表进行排序。 然后使用pd.concat
连接数据帧列表,最后将其导出到output.txt
import re
import glob
import pandas as pd
myfiles = glob.glob('file*')
myfiles.sort(key=lambda s: re.findall(r'\d+', s)[0])
df = pd.concat([pd.read_csv(myfile, header=None) for myfile in myfiles], axis=1)
df.to_csv('output.txt', index=None, header=None, sep=' ')
import glob
myfiles = sorted(glob.glob('file*'))
print(myfiles)
num_lists = []
for file in myfiles:
#from here i cannot proceed
with open(file, "r") as fin:
num_lists.append(fin.readlines())
print(num_lists)
aligned_lists = zip(num_lists[0], num_lists[1], num_lists[2])
with open("output.txt", "w") as fout:
for lst in aligned_lists:
print(lst)
new_lst = list(map(str.strip, lst))
print(new_lst)
fout.write(" ".join(new_lst) + "\n")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.