AZDDKKS
AZDDKKS

Reputation: 41

python How do I import multiple .txt files in a folder to add characters to each .txt file?

There are text files of various names in the folder 'a'. I want to read all of these text files and add the letter 'b' to each text file. What should I do?

cwd = os.getcwd()
input_dir = os.path.join(cwd, "my .txt files dir")

sorts = sorted(glob(input_dir), key = lambda x:(len(x) , x))

for f in sorts :
    f = open(input_dir, 'a')
    data = "add text"
    f.write(data)
    f.close()

Upvotes: 0

Views: 1947

Answers (3)

Iakovos Belonias
Iakovos Belonias

Reputation: 1373

Avoid to open files with

f = open(input_dir, 'a')
f.close()

Instead

with open(input_dir, 'a') as inputFile:
    Do something

Also what you want is

import os
import glob  # We will use this module to open only .txt files

path = 'your/path'

for filename in glob.glob(os.path.join(path, '*.txt'))
    with open(filename, 'a') as inputFile:
        inputFile.write('b')

Upvotes: 0

Gagiu Filip
Gagiu Filip

Reputation: 228

Like the others said, this is an easy question that could easily be find on google. Anyway here's how to do it:

from os import listdir
from os.path import isfile, isdir, join

files = [file for file in listdir("files") if isfile(join("files", file))]
        directories = [directory for directory in listdir("files") if isdir(join("files", directory))]

print(files)

for file_name in files:
    try:
        file = open("files/" + file_name, "a")
        file.write("b")
        file.close()
    except IOError as err:
        print("Could not open file because : ", err)

Replace "file" with the directory where your files are or the path to that directory like "directory0/directory1/directory_with_files"

Upvotes: 1

potoo
potoo

Reputation: 64

Append data to file:
- first: get all file in folder a.
- second: find extension with .txt.
- third: open it and do something('append', or 'rewrite').

Demo:

import os

# your .txt files dir
path = 'a'
# append data what you want
appendData = 'b'

fileNames = list(os.walk(path))[0][2]
fileNames.sort(key=len)
fileNums = len(fileNames)

# your dst file extension
fileExt = '.txt'
# # Extract extension from filename
# fileExt = os.path.splitext(fileNames[0])[1]

for fileName in fileNames:
    if fileName.endswith(fileExt):
        fileFullPath = os.path.join(path, fileName)
        with open(fileFullPath, 'a') as f:
            f.write(appendData)

Upvotes: 3

Related Questions