Using Python To Interact With The Operating System
Using Python To Interact With The Operating System
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()
file = open(“filename.txt”)
print(file.readlines()) returns a list containing all the lines
file.close()
open “r” read, “w” write, “a” append, “r+” read, write
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)
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