I have text files(file1,file2,file3...) in a directory i want to sort based on file names and arrange the files side by side in a separate text file.
cat file1 cat file2 cat file3
1 4 8
3 5 1
4 6 3
expected output
cat output.txt
1 4 8
3 5 1
4 6 3
My code:
import glob
myfiles = glob.glob('file*')
for file in myfiles:
#from here i cannot proceed
CodePudding user response:
You can sort the file list by the integer in it. Then use pd.concat
to concat list of dataframes and at last export it to 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=' ')
CodePudding user response:
- You need to sort the files according to their names
- According to your requirements, use Zip function to align them
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")