Friday, May 13, 2022

[FIXED] How to append text to multiple files in python?

Issue

There are multiple examples how one can append text to a SINGLE file.

What I would like to do is append the same text to ALL the files in the "folder1".

This is what I have tried so far.

import os

dir = (r'C:\Users\User1\Desktop\folder1')

for i in os.listdir(dir):
        file = open(dir, 'a')
        file.write("My desired text" + "\n")

file.close()

What I am getting right now is this error:

PermissionError: [Errno 13] Permission denied: 'C:\Users\arvydas\Desktop\nice_name'

I have:

  • ran the script through cmd on windows as administrator
  • made sure that the folder name is not the same as the names of the files -checked the folder permissions..

whats wrong?


Solution

Your file directs to your folder, sure. So if you use that path to create a folder

file = open(dir, 'a')

you are basically doing

file = open(r'C:\Users\User1\Desktop\folder1', 'a')

And obviously, that's not what you want. I see that you are iterating through the folders files though, with i. So why not use that? Additionally, using plain i wont work. You have to combine that with your dir.

import os

dir = (r'/Users/aspera/Documents/Python/Py_Programs/tests/my_folder')

for i in os.listdir(dir):
        file = open(f"{dir}/{i}", 'a')
        file.write("My desired text" + "\n")

file.close()


Answered By - BuddyBob
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.