Home > Software design >  How do I read the information from multiple txt files?
How do I read the information from multiple txt files?

Time:05-29

This is my code for reading my files from my folder but idk how can I read its information of each one.

import os

def readfiles(folder):

    for file in os.listdir(folder):
        print(file)
        if os.path.isdir(os.path.join(folder,file)):
            devolverArchivos(os.path.join(folder,file))

readfiles("/home/citlali/Modelos")

CodePudding user response:

You can use os.walk() like below:

import os

temp = {}

for subdir, dirs, files in os.walk("."):
    for file in files:
        filepath = subdir   os.sep   file
        if filepath.endswith(".txt"):
            # Your function goes here!
            with open(filepath) as f:
                temp[filepath] = f.readlines()

CodePudding user response:

You could read text files using open("text.txt").read().splitlines(). For example

import os

def readfiles(folder):
    result1 = []
    result2 = []
    for file in os.listdir(folder):
        if file[-4:] == '.txt':
            result1.append(open(file).read().splitlines())
            result2.extend(open(file).read().splitlines())
    print(result1)
    print(result2)

readfiles("/home/citlali/Modelos")

Depending on how you would like to compile the results, list.append() will append the list of text lines, whereas list.extend() will add individual text lines (ie, merge 2 lists into 1).

To write all text files into 1 text file, you could try:

def readfiles(folder):
    with open('result.txt', 'a') as write_file:
        for file in os.listdir(folder):
            if file[-4:] == '.txt':
                write_file.write(', '.join(open(file).read().splitlines()))
                write_file.write('\n')
    write_file.close()

readfiles("/home/citlali/Modelos")
  • Related