Python - Files
-1. Files Example
import datetime
import os
import shutil
import time
from os import path
from zipfile import ZipFile
def main1():
# create a new file
f = open("textfile.txt", "w+")
# write file
for i in range(10):
f.write("This is line" + str(i) + "\r\n")
f.close()
# append in a file
f = open("textfile.txt", "a")
for i in range(10):
f.write("This is added line" + str(i) + "\r\n")
f.close()
# open file for open
f = open("textfile.txt", "r")
if f.mode == 'r':
# contents = f.read()
# print(contents)
fl = f.readlines()
for x in fl:
print(x)
f.close()
def main2():
# working with OS patch
print(os.name)
print(str(path.exists("textfile.txt")))
print(str(path.isfile("textfile.txt")))
print(str(path.isdir("textfile.txt")))
print(str(path.realpath("textfile.txt")))
print(str(path.split(path.realpath("textfile.txt"))))
t = time.ctime(path.getmtime("textfile.txt"))
print(t)
print(datetime.datetime.fromtimestamp((path.getmtime("textfile.txt"))))
td = datetime.datetime.now() - datetime.datetime.fromtimestamp(path.getmtime("textfile.txt"))
print(str(td))
print(str(td.total_seconds()) + " seconds")
def main3():
# shell methods
if path.exists("textfile.txt"):
src = path.realpath("textfile.txt")
dst = src + ".bak"
shutil.copy(src, dst)
shutil.copystat(src, dst)
# os.rename("textfile.txt","textfile2.txt")
# root_dir, tail=path.split(src)
# shutil.make_archive("archive","zip",root_dir)
with ZipFile("testzip.zip", "w") as newzip:
print("===")
newzip.write("textfile.txt")
newzip.write("textfile.txt.bak")