Opening Hours :7AM to 9PM
In this tutorial, you'll learn about file and directory management in Python, i.e. creating a directory, renaming it, listing all directories, and working with them.
>>> import os >>> os.getcwd() 'C:\\Program Files\\PyScripter' >>> os.getcwdb() b'C:\\Program Files\\PyScripter' The extra backslash implies an escape sequence. The print() function will render this properly. >>> print(os.getcwd()) C:\Program Files\PyScripter
>>> os.chdir('C:\\Python33') >>> print(os.getcwd()) C:\Python33
>>> print(os.getcwd()) C:\Python33 >>> os.listdir() ['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'tcl', 'Tools'] >>> os.listdir('G:\\') ['$RECYCLE.BIN', 'Movies', 'Music', 'Photos', 'Series', 'System Volume Information']
>>> os.mkdir('test') >>> os.listdir() ['test']
>>> os.listdir() ['test'] >>> os.rename('test','new_one') >>> os.listdir() ['new_one']
>>> os.listdir() ['new_one', 'old.txt'] >>> os.remove('old.txt') >>> os.listdir() ['new_one'] >>> os.rmdir('new_one') >>> os.listdir() [] Note: The rmdir() method can only remove empty directories. In order to remove a non-empty directory, we can use the rmtree() method inside the shutil module. >>> os.listdir() ['test'] >>> os.rmdir('test') Traceback (most recent call last): ... OSError: [WinError 145] The directory is not empty: 'test' >>> import shutil >>> shutil.rmtree('test') >>> os.listdir() []
import os def myfun(): os.chdir("C:\\Users\\Lenovo\\Desktop\\abc") f1=open("a.txt", mode="r") x=int(f1.read()) os.chdir("C:\\Users\\Lenovo\\Desktop\\xyz") f2=open("b.txt" ,mode="r") y=int(f2.read()) z=x+y print(z) os.chdir("C:\\Users\\Lenovo\\Desktop") os.mkdir("sat") os.chdir("C:\\Users\\Lenovo\\Desktop\\sat") f3=open("c.txt" ,mode="w") f3.write(str(z)) f1.close() f2.close() f3.close() if __name__=="__main__": myfun()