k0b0's record.

Computer Engineering, Arts and Books

Introduction to Python. System programming [Process files]

System programming "Process files with python."

List of functions to use

Function name Description
open() Open the file.
exists() Check the existence of the file.
isfile() It checks whether the argument is a file or not.
isdir() It checks whether the argument is a directory or not.
isabs() It checks whether the argument is an absolute path or not.
copy() Copy argument 1 to argument 2.
rename() Change the file name.
chmod() Change permissions.
abspath() Get path name.
remove() Remove the file

Sample program to process the file

### Sample program to process the file.

import os
import shutil

# open() : open the file.
fout = open('MY_FILE.txt', 'wt')

print('MY_FILE, I created file.', file=fout);
fout.close()

# exists() : Check the existence of the file.
print("os.path.exists('MY_FILE.txt') : %s" % os.path.exists('MY_FILE.txt'))
print("os.path.exists('./MY_FILE.txt') : %s" % os.path.exists('./MY_FILE.txt'))
print("os.path.exists('tmp') : %s" % os.path.exists('tmp'))
print("os.path.exists('.') : %s" % os.path.exists('.'))
print("os.path.exists('..') : %s" % os.path.exists('..'))

# isfile() : It checks whether the argument is a file or not.
name = 'MY_FILE.txt'
print("os.path.isfile(name) : %s" % os.path.isfile(name))

# isdir() : It checks whether the argument is a directory or not.
print("os.path.isdir(name) : %s" % os.path.isdir(name))

# isabs() : It checks whether the argument is an absolute path or not.
print("os.path.isabs(name) : %s" % os.path.isabs(name))

# copy() : Copy argument 1 to argument 2.
shutil.copy('MY_FILE.txt', 'MY_FILE_2.txt')
print("os.path.exists('MY_FILE_2.txt') : %s" % os.path.exists('MY_FILE_2.txt'))

# rename() : Change the file name.
os.rename('MY_FILE_2.txt', 'MY_FILE_3.txt')
print("os.path.exists('MY_FILE_3.txt') : %s" % os.path.exists('MY_FILE_3.txt'))

# chmod() : Change permissions.
os.chmod('MY_FILE.txt', 0o755)

# abspath() : Get path name.
print("os.path.abspath('MY_FILE.txt')) : %s" % os.path.abspath('MY_FILE.txt'))

# remove() : Remove the file
os.remove('MY_FILE.txt')
print("os.path.exists('MY_FILE.txt') : %s " % os.path.exists('MY_FILE.txt'))