Operating files
Opening file list
Using os
module1
2
3
4
5
6import os
print os.listdir('.') # file list of present directory
print
print os.listdir('../') # file list of parent directory
Recognizing file’s category
os.path
module recognizes and returnsTrue
orFalse
1
2
3
4
5
6
7
8
9
10
11
12
13import os
def filetype(fpath):
print fpath, ":",
if os.path.isfile(fpath):
print 'Regular file'
if os.path.isdir(fpath):
print 'Directory'
if os.path.islink(fpath):
print 'Symbolic link'
flist = os.listdir('.')
for fname in flist:
filetype(fname)
Permission about file
Learning permission about file
os.access(filepath, mode)
- the values we can put for
mode
os.F_OK
: testing if the file existsos.R_OK
: testing about reading permissionos.W_OK
: testing about writing permissionos.X_OK
: testing about opening or executing permission
- the values we can put for
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import os
def fileaccess(fpath):
print fpath, ':',
if os.access(fpath, os.F_OK):
print 'Exists',
else:
return
if os.access(fpath, os.R_OK):
print 'R',
if os.access(fpath, os.W_OK):
print 'W',
if os.access(fpath, os.X_OK):
print 'X',
print
flist = os.listdir('.')
for fname in flist:
fileaccess(fname)Chagning the Permission for the file
os.chmod(filepath, mode)
1
2import os
os.chmod('sample.txt', 0777)
Manipulating files
Chagning the name of the file
os.rename(old_filepath, new_filepath)
1
2
3
4
5import os
os.rename('t.txt', 't1.txt')
print os.access('t.txt', os.F_OK) # checking if the file exists
print os.access('t1.txt', os.F_OK)Moving the file
os.rename(oldfilepath, new_filepath)
1
2
3
4
5import os
os.rename('t.txt', 'example/t1.txt')
# checking if the file exists
print os.access('example/t1.txt', os.F_OK)
Copying the file
shutil
module is usedshutil.copyfile(src_filepath, dest_filepath)
1
2
3
4import os
import shutil
shutil.copyfile('sample.txt', 'sample_new.txt')
print os.access('sample_new.txt', os.F_OK)
Manipulating the path of the file
Changing relative path to absolute path
os.path.abspath
- relative path- no matter the existance of the file, it changes the path to absolute path
1
2import os
print os.path.abspath('o.txt')
- no matter the existance of the file, it changes the path to absolute path
Checking if the file exists in the given path
os.path.exists(filepath)
Dividing path name
Dividing path and file’s name
1
2
3
4f = '/Users/booski/git/python/t.txt'
print os.path.basename(f) # extracting only the file's name
print os.path.dirname(f) # extracting the directory's nameDividing path and file’s name by one line -
basename
anddirname
are made in a tuple1
print os.path.split(f)
Dividing drive’s name and file path in MS windows
1
print os.path.splitdrive(f)
Dividing extension -
path
andextension
are made in a tuple1
print os.path.splitext(f)