Using Python to interact with the Operating System
Google IT Automation with Python, Coursera
Reading Files
https://docs.python.org/3/library/functions.html#open
file = open(“filename.txt”)
print(file.readline()) read single line
file.read() read whole file
file.close()
with open(“filename.txt”) as file: automatically close the file
print(file.readline())
with open(“filename.txt) as file:
for line in file:
print(line)
file = open(“filename.txt”)
print(file.readlines()) returns a list containing all the lines
file.close()
with open(“filename.txt”, “w”) as file: automatically close the file
file.write(“It was a dark”)
open “r” read, “w” write, “a” append, “r+” read, write
Working with file & directory
Import os
Os.remove(“novel.txt”)
Os.rename(“one.txt”, “two.txt”)
Os.path.exists(“file.txt”) exist file
Os.path.getsize(“file.txt”)
Os.path.getmtime(“file.txt”) time created
Import datetime
Timestamp = os.parth.getmtime(“file.txt”)
Os.path.abspath(“file.txt”) full path
Os.getcwd() current dir
Os.mkdir(“dir”)
Os.chdir(“dir”) change dir
Os.rmdir(“dir”)
Os.listdir(“dir”) list file in dir
Os.path.isdir
CSV files
Import csv
F = open(“csv.txt”)
Csv_f=csv.reader(f)
For row in csv_f:
Name, phone, role = row same amount of variable in left side
Print(“{} {}”.format(name, phone)
f.close()
Generating csv
Hosts = [[“fsdjsajf”, “djfdj”],[“djfdj”, “asfdsf”]]
With open(‘file.csv’, ‘w’) as host_csv:
Writer = csv.writer(host_csv)
Writer.writerrows(hosts)
Reading and writing csv with Dictionary
With open(‘file.csv’, ‘w’) as host_csv:
reader = csv.DictReader(host_csv)
for row in reader:
print({} {}).format(row[“name”], row[“user”])
csv dictionary
name,version,status,users
Mail,4.35,production,345
Week 4
Standard stream. Stdin, stdout, stderr
Environmental Variable
Os.environ.get(“HOME”, “”) no error if there is no key
Export variable=value assign variable
Passing argument
Pythonprogramming.py one two three
Import sys
Print(sys.argv) print one two three(separate element list)
Exit status
Echo $? From shell. 0 no error
Python script sys.exit(number) whatever number we want
Running system commands in Python
Sub processes
subprocess.run(["date"])