Detail the file and directory operations in python

  • 2020-06-12 09:32:08
  • OfStack

Detail the file and directory operations in python

1 Gets the current path

1. Code 1


>>>import os
>>>print('Current directory is ',os.getcwd())
Current directory is D:\Python36

2. Code 2

If the above script is written to a file to run


Current directory is E:\python\work

Get the contents of the directory

Python code


>>> os.listdir (os.getcwd()) 
['DLLs','Doc','include','Lib','libs','LICENSE.txt','NEWS.txt','PyOpenGL-wininst.log','python.exe','
python3.dll','python36.dll','pythoncom36.dll','pythonw.exe','pywin32-wininst.log','pywintypes36.dll',
'RemovePyOpenGL.exe','Removepywin32.exe','Scripts','tcl','Tools','vcruntime140.dll'] 

3 Create directory


>>>import os
>>> os.mkdir('temp')

4 Delete directory


>>> os.rmdir('temp')

5 Determine if it is a directory


>>> os.path.isdir('E:\\python')
True

6 Determine if it is a file


>>> os.path.isfile('E:\\python\\work\\test.py')
True

Above is the python file and directory operation of the simple operation, if you have any questions can refer to the relevant information on this site, welcome to leave a message to discuss! Thank you for reading, I hope to help you, thank you for your support to this site!


Related articles: