Using Python to interact with the Operating System
Google IT Automation with Python, Coursera
Reading Files
[Link]
file = open(“[Link]”)
print([Link]()) read single line
[Link]() read whole file
[Link]()
with open(“[Link]”) as file: automatically close the file
print([Link]())
with open(“[Link]) as file:
for line in file:
print(line)
file = open(“[Link]”)
print([Link]()) returns a list containing all the lines
[Link]()
with open(“[Link]”, “w”) as file: automatically close the file
[Link](“It was a dark”)
open “r” read, “w” write, “a” append, “r+” read, write
Working with file & directory
Import os
[Link](“[Link]”)
[Link](“[Link]”, “[Link]”)
[Link](“[Link]”) exist file
[Link](“[Link]”)
[Link](“[Link]”) time created
Import datetime
Timestamp = [Link](“[Link]”)
[Link](“[Link]”) full path
[Link]() current dir
[Link](“dir”)
[Link](“dir”) change dir
[Link](“dir”)
[Link](“dir”) list file in dir
[Link]
CSV files
Import csv
F = open(“[Link]”)
Csv_f=[Link](f)
For row in csv_f:
Name, phone, role = row same amount of variable in left side
Print(“{} {}”.format(name, phone)
[Link]()
Generating csv
Hosts = [[“fsdjsajf”, “djfdj”],[“djfdj”, “asfdsf”]]
With open(‘[Link]’, ‘w’) as host_csv:
Writer = [Link](host_csv)
[Link](hosts)
Reading and writing csv with Dictionary
With open(‘[Link]’, ‘w’) as host_csv:
reader = [Link](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
[Link](“HOME”, “”) no error if there is no key
Export variable=value assign variable
Passing argument
[Link] one two three
Import sys
Print([Link]) print one two three(separate element list)
Exit status
Echo $? From shell. 0 no error
Python script [Link](number) whatever number we want
Running system commands in Python
Sub processes
[Link](["date"])