Access OS interfaces
import os
import shutil
from os import path
from shutil import make_archive
from zipfile import ZipFile
# make a duplicate of an existing file
if path.exists ("w1.txt"):
# get the path to the file in the current directory
src = path.realpath ("w1.txt")
# separate the path part from the filename
fpath, fname = path.split (src) ## :h :t
print ( "path:", fpath )
print ( "file:", fname )
# let's make a backup copy by appending "bak" to the name
dst = src + '.bak'
# now use th eshell to make a copy of the file
shutil.copy (src,dst)
# copy over the permissions, modification times, and other info
shutil.copystat (src,dst)
# rename the original file
os.rename ("w1.txt", "new.txt")
# common use
os.getcwd()
os.chdir()
os.remove('file_to_remove.txt')
Create Archive Zip File
# now put things into a ZIP archive
fpath, fname = path.split (src) ## :h :t
shutil.make_archive ("archive", "zip", fpath)
# more fine_grained constrol over ZIP files
with ZipFile ("w1.zip", "w") as newzip:
newzip.write ("new.txt")
newzip.write ("w1.txt.bak")
os.system( "/bin/cp w1.txt.bak w1.txt" )
Find out OS system
import os print (os.name) ## always posix for linux, windows or OS X import platform platform.platform()
os.path
import os.path
os.path.join ('path_name', 'sub_path', 'file_name')
>>> 'path_name/sub_path/file_name'
## on window system
os.path.join ('c:','path_name', 'sub_path', 'file_name')
>>> 'path_name\sub_path\file_name'
os.path.exists ('path_or_file_name')
os.path.isfile ('path_or_file_name')
os.path.isdir ('path_or_file_name')
os.path.islink ('path_or_file_name')
os.popen
import os filename = 'book.txt' cmd = 'ls '+ filename fp = os.popen( cmd ) res = fp.read() stat = fp.close()
No comments:
Post a Comment