0

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.

Community
  • 1
  • 1
Frasher Gray
  • 222
  • 2
  • 14
  • 1
    which line is throwing that error? That's where to start looking. – mauve Dec 09 '19 at 18:26
  • [Maybe not a dupe but helpful](https://stackoverflow.com/questions/955941/how-to-identify-whether-a-file-is-normal-file-or-directory-using-python). Do `os.path.isfile()` before opening it as a file and `readlines`ing. `os.walk` may be easier as `os.listdir` if you just want the files in a directory. – ggorlen Dec 09 '19 at 18:28
  • 8
    replace your loop line with: `for _, _, files in os.walk(...):` – Brian Dec 09 '19 at 18:29
  • 1
    See this lovely [debug](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) blog for help. `print files` between your two `for` statements will show your first error. `print` is your debugging friend. It will also help if you follow the code in the question you cited, instead of changing things you don't *quite* understand ... yet. `print` will help fix that, too. – Prune Dec 09 '19 at 18:43

1 Answers1

3

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
Frasher Gray
  • 222
  • 2
  • 14