Тёмный

How To Merge Text Files in Python 

PikFix
Подписаться 58
Просмотров 2,9 тыс.
50% 1

The code I used for this solution is-
import os
def get_dir_files(dir):
all_files = os.listdir(dir)
txt_files = []
for file in all_files:
full_path = os.path.join(dir, file)
if file.find('.txt') != -1:
txt_files.append(full_path)
else:
pass
return txt_files
def get_united_file(all_files):
with open(r'C:\Users\karin\Desktop\Work\PikFix\TextCombiner\united.txt', 'w') as outfile:
for file in all_files:
with open(file) as infile:
outfile.write(infile.read() + '
')
def main():
dir_path = r'C:\Users\karin\Desktop\Work\PikFix\TextCombiner'
all_files = get_dir_files(dir_path)
get_united_file(all_files)
if _name_ == '__main__':
main()

Опубликовано:

 

8 июл 2022

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 3   
@user-ws7oj9sk3f
@user-ws7oj9sk3f Год назад
thanks a lot for the great video.if you have had the possibility to better explain the lines of code it would have been amazing. I have to merge only some portion of each txt file. in particular data start with the keyword "table:" and finish with another keyword "legenda". so i need to import and merge only the record between these two keywords. could you please give me an advice to modify the script? thanks a lot
@oncledan8509
@oncledan8509 2 года назад
Hi ! This was a very instructive video, ...however (Yes, there is a small problem on my side) I have 94 files, named « Dict4-01 » to « Dict4-94 » that I want to merge. It merges them all right, BUT it seems they are merged randomly. Starts with 26, 32 33, 27, 31, 35 ... and so on. Now, I'm running Python 3 on a Mac, but I don't think this is a reason why it acts this way. Is there another way to do this, making sure all gets merges in the right sequence? My code is the same as yours, except lines 22 and 29, of course. It reflects my path and filename. Thank you for your time and I'll await your reply. Meanwhile, have a great weekend and I hope to read from you soon. Yours truly, Daniel.
@pikfix3292
@pikfix3292 2 года назад
Hello Daniel, Thank you for your question! You can add this line --> txt_files.sort() --> to the end of "get_dir_files" function. By using sort you can control the order of a list in python so that when you loop over the file list in the "get_united_file" function it will be in the correct order. If you want to reverse the order you can do it like so --> txt_files.sort(reverse=True) I hope this answers your question. Great weekend to you too, Karin 🙂
Далее
Scripting with Python - Modify a TXT file
19:00
Просмотров 50 тыс.
Good deed #standoff #meme
00:15
Просмотров 651 тыс.
#5 Read and process multiple text files in Python
9:38
Combine text files in Windows - 4 Methods
8:40
Просмотров 16 тыс.