Read and Write Files

For reading and writing files with Python, first you need to use open function, inside the open function set the path of the file and then set the mode of the file. The mode can be 'r' only to read the file, 'w' only to writing in the file, 'r+' opens the file for both reading and writing, and 'a' opens the file for appending.

Examples

Open file

	
>>> my_file = open('D:\\test.txt','r')
>>> my_file.read()
'This is a test file!\nSecond line of the file.'
>>> 

Read lines from a text file using open function

	
>>> with open('D:\\test.txt','r') as x:
	for line in x:
		line

		
'This is a test file!\n'
'Second line of the file.'
>>> 

Write lines in a text file

	
>>> with open('D:\\test.txt','w') as x:
   x.write('First file line\nSecond file line')

	
32
>>> with open('D:\\test.txt','r') as x:
	for line in x:
		line

		
'First file line\n'
'Second file line'
>>>