Home > Software design >  Python not working when using pass in loop
Python not working when using pass in loop

Time:11-06

I am making simple program that adds a piece of text to every file in the folder however this code is also adding text to my python file so I made a if statement that stops this from happening. But now the script does not work at all.

import os

def main():
    for file in os.listdir():
        if file == 'main.py' or 'Password.txt:
            pass
        else:
            with open(file, 'a') as file:
                try:
                    file.write("hello")
                    print("sucess")
                except:
                    print("error")

main()

I have no idea why this is not working. Thank you very much.

I expected this script to add hello to the end of every file but it does nothing at all. It worked before I added the if statement to stop it from adding hello the the python file.

Edit: When I get rid of the or statement the code works perfectly fine. I have no idea why this is happening.

CodePudding user response:

this setup works for me:

main.py

import os

def main():
    for file in os.listdir():
        if file == 'main.py':
            pass
        else:
            with open(file, 'a') as file:
                try:
                    file.write("hello")
                    print("sucess")
                except:
                    print("error")

if __name__ == "__main__":
    main()

tree

.
├── main.py
└── test.txt

test.txt

  • empty file before running
  • after:
hello

from the terminal I'm running

python3 main.py

CodePudding user response:

It looks like it's a syntax error "now the script does not work at all." Next time include the error log

        if file == 'main.py' or 'Password.txt':
            pass

Consider using IntelliSense: Edit your code with auto-completion, code navigation, syntax checking and more

  • Related