Объединить несколько текстовых файлов в один текстовый файл, используя python

Вопрос:предположим, что у нас много текстовых файлов: file1: abc def ghi file2: abc def ghi file3: adfafa file4: ewrtwe rewrt wer wrwe Как мы можем сделать один текстовый файл, как показано ниже: результат: abc def ghi ABC DEF GHI adfafa ewrtwe rewrt wer wrwe Связанный код может быть: import csv import glob files = glob.glob('*.txt')

Вопрос:

предположим, что у нас много текстовых файлов:

file1:

abc def ghi

file2:

abc def ghi

file3:

adfafa

file4:

ewrtwe rewrt wer wrwe

Как мы можем сделать один текстовый файл, как показано ниже:

результат:

abc def ghi ABC DEF GHI adfafa ewrtwe rewrt wer wrwe

Связанный код может быть:

import csv import glob files = glob.glob(‘*.txt’) for file in files: with open(‘result.txt’, ‘w’) as result: result.write(str(file)+’n’)

После этого? Любая помощь?

Лучший ответ:

Вы можете прочитать содержимое каждого файла непосредственно в методе записи дескриптора выходного файла следующим образом:

import glob read_files = glob.glob(«*.txt») with open(«result.txt», «wb») as outfile: for f in read_files: with open(f, «rb») as infile: outfile.write(infile.read()) Ответ №1

Вы можете попробовать что-то вроде этого:

import glob files = glob.glob( ‘*.txt’ ) with open( ‘result.txt’, ‘w’ ) as result: for file_ in files: for line in open( file_, ‘r’ ): result.write( line )

Должно быть прямо прочитано.

Ответ №2

Модуль fileinput идеально подходит для этого варианта использования.

import fileinput import glob file_list = glob.glob(«*.txt») with open(‘result.txt’, ‘w’) as file: input_lines = fileinput.input(file_list) file.writelines(input_lines) Ответ №3

Также возможно объединить файлы, включив команды ОС. Пример:

import os import subprocess subprocess.call(«cat *.csv > /path/outputs.csv») Ответ №4filenames = [‘resultsone.txt’, ‘resultstwo.txt’] with open(‘resultsthree’, ‘w’) as outfile: for fname in filenames: with open(fname) as infile: for line in infile: outfile.write(line)

Оцените статью
Добавить комментарий