Search code examples
pythonfiledirectoryediting

How Would You Go Through a Directory and Get the Files From Them With a For Loop?


I am trying to get all the files from a directory and edit them, one by one, but I cannot figure out how. I tried looking at the question here, but the answer wasn't quite what I needed. Here is my code:

import os
playeritems = 'PlayerFiles/PlayerItems'
for files in os.walk(playeritems):
    for file in files:
      with open(os.path.join(file), 'r') as t:
        t_reading = t.readlines()
        for i in t_reading:
          #Do what I need to do to the line of code.
      

I am trying to look through each file and change some of the lines in it, but it keeps giving me the error:

IsADirectory: Is a directory on with open(os.path.join(file), 'r') as t:

I got my current code from the question above, so if there are other errors in it, I will fix them as soon as I find them.


Solution

  • I am not including the sub-directories possibility or the directories possibility to look for in playeritems. My code should look like:

    for _, __, files in os.walk(playeritems):
        for file in files:
          with open(os.path.join(playeritems, file), 'r') as t:
            #Do stuff to the file