Search code examples
pythoniolistdir

How to read all .txt files in a folder and append its contents into one .txt file, using Python?


I have a folder with multiple .txt files. for every .txt file in the folder, I want to take one line of the content and append them in a new .txt file. How to do this in Python? I'm new to this, also new to publicly asking questions.this is all I got.

import os    
Folder = os.listdir('E:\\Project\\tests')   
f = open('outputFile.txt', 'a')   

for file in Folder:   
    file.read()   
    for i in file:   
        f.write(i[1] + '\n')   
f.close()

Solution

  • The problem in your code that you don't open the files to read.

    Try this one:

    from os import listdir
    from os.path import isfile, join 
    
    folder_path = 'E:\\Project\\tests'
    
    # get the full names of all the txt files in your folder   
    files = [join(folder_path, f) for f in listdir(folder_path) if isfile(join(folder_path, f)) and f.endswith(".txt")] 
    
    f = open('outputFile.txt', 'a')   
    
    for file in files:   
        line = open(file,"r").readlines()[1] # line will be equal to the second line of the file
        f.write(line + '\n')   
    f.close()