Working with Files in Python:

Python uses file objects to interact with external files on our computer. These file objects can be any sort of file we have on our computer, whether it be an audio file, a text file, emails, Excel documents, etc.


File Path:

	
#  get the path of current working directory  : 

	pwd
	
	
	#  using os module  : 
	
	import os
	os.getcwd()
	
	
#  Relative path of a directory  : 

	import os
	os.path.relpath(path, [start])
	
	#  Example  : set the path of current project. 
	proj_main_dir= os.path.relpath("C:\\ProjectFile\\path")
	
	

Listing Files in a directory :

	
#  list all the files and folder of current directory  : 

	os.listdir()
	
	#  list all the files and folder of given path  : 
	
	os.listdir("path\\to\\the\\directory")
	

Open a File in Python:

Python uses open() function to open a file. it takes two parameter; filename and mode .


	
	my_file = open("C:\\path\\of\\the\\file.txt", "r") 
	
	my_file = open("C:\\path\\of\\the\\file.txt", "rt") 
	
	

Reading a File in Python:

Closing a File in Python:

We should always close our files after working on it. in some cases, due to buffering, changes made to a file may not show until we close the file.

	
	my_file = open("C:\\path\\of\\the\\file.txt", "r")
	
	print(my_file.readline())
	
	f.close()
	

Writing to a file in Python:

Moving a file in Python:

We can use shutil module to move the files from one location to another. However we need to keep in mind that we need to have the proper permission.

Delete a file in Python:

Delete a file / folder in Python:

Check if file exist in Python:

Iterating through a file in Python:


Walking through a directory :