Section 1.3:: File System
Section 1.3:: File System
3:
File System
I. BEN NASR
File System
• Identify the platform running a Python • sys.platform
script • os: os.getcwd, os.chdir,
• Get the current working directory os.listdir, os.mkdir,
• Change the current working directory os.rmdir, os.rename
• List the content of the current working • os.path: os.path.abspath,
directory os.path.exists,
• Create and remove directories os.path.isfile, os.path.isdir
• Rename files and directories
• Recognize the difference between
relative and absolute paths
• Test whether a file or path exists
Section 1.3
The plateform module
import platform
Platform Functions
system: Windows
Print('node :', platform.node() )
DESKTOP-IM03TR9
print ('release :’, platform.release())
10
Print ( 'version :’, platform.version())
'10.0.18362'
print 'machine :', platform.machine()
AMD64
print 'processor:', platform.processor()
• To find out which directory in python you are currently in, use the
getcwd() method.
>>> os.getcwd()
'C:\\Users\\ben nasr\\AppData\\Local\\Programs\\Python\\Python37’
>>>print(os.getcwd())
• cwd is for current working directory in python. This returns the path of
the current python directory as a string in Python.
Changing Current Python Directory
>>> os.chdir('C:\Users\lifei')
Python List Directories and Files
1) To get the contents of a directory into a python list, we use the listdir() method.
>>> os.listdir() ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe',
'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
2) How to Create Python Directory?
• We can also create new python directories with the mkdir() method.
>>> os.mkdir('Photos')
>>> os.listdir() ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'Photos',
'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll’]
3) How to Rename Python Directory?
• To rename directories in python, we use the rename() method. It takes two
arguments- the python directory to rename, and the new name for it.
>>> os.rename('Photos’,’Photos 2020’)
>>> os.listdir() ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'Photos
2020', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
Python List Directories and Files
3) os.path.isdir()
If we want to confirm that a given path points to a directory, we can use the os.path.dir()
function
>>>print ("Is it Directory?" + str(path.isdir('guru99.txt')))
>>>print ("Is it Directory?" + str(path.isdir('myDirectory')))
os.path
• Parameter:
Path: A path-like object representing
3) abspath(path) a file system path.
• Return Type: This method returns a
normalized version of the pathname
path.
• Syntax: os.path.abspath(path)
Section
Example 1
# Python program to demonstrate
# os.path.abspath()
import os.path
# file name
file_name = 'GFG.txt'