Commands and Files

Passing arguments to a Python program

cat file1.txt
python3 people.py Gosho Pesho Tosho
Arguments: 4
Arg 1: people.py
Arg 2: Gosho
Arg 3: Pesho
Arg 4: Tosho

The sys library

The OS (Operating System) library

  • Working with files and directories
  • Getting the root path
  • Getting the current directory
>>> path = os.getcwd()
>>> for entry in os.scandir(path):
...    if not entry.name.startswith('.') and entry.is_file():
...        print(entry.name)

Reading/Writing files

>>> f = open("foo.py", "r")
>>> f.read()
'def a(): pass'
>>> f.close()
>>> f = open("foo.py", "r")
>>> f.readlines()
['def a(): pass']
with open("foo.py", "w") as f:
...     f.write("def a(): pass")
with open("foo.py", "a") as f:
...     f.write("print(a())")

What does the

if __name__ == "__main__": do?

if __name__ == "__main__":
    print("In {0} module".format(__name__))

Python 101 9th Commands and Files

By Hack Bulgaria

Python 101 9th Commands and Files

  • 911