Python Writing Into File

Writing into file

Python provides write(data) function to write the given data which is a string into the file and it returns the number of characters written into file.

Syntax
Syntax:
	var=file_object.write(data)

where,

  • data is the content which is a string to be written into a file
  • var is a variable assigned with number characters written into the file
CODE/PROGRAM/EXAMPLE
//Example:

	fhr=open("data.txt","r")
	data =fhr.read()
	print("Before writing:")
	print(data)
	fhr.close()

	fhw=open("data.txt","w")
	num=fhw.write("this new first line written\n")
	num1=fhw.write("this new second line written\n")
	print("num:",num)
	print("num1:",num1)
	fhw.close()

	fhr=open("data.txt","r")
	data =fhr.read()
	print("After writing:")
	print(data)
	fhr.close()
	
Output:
	Before writing:
	this is first line
	you are reading the second line
	now you are dealing with third line
	num: 28
	num1: 29
	After writing:
	this new first line written
	this new second line written
Notepad

Note: The file ‘data.txt’ is opened in write mode, so previous content of file is truncated and it contains only two lines after writing into it.

CODE/PROGRAM/EXAMPLE
//Another example:

	fhr=open("data.txt","r")
	data =fhr.read()
	print("Before writing:")
	print(data)
	fhr.close()

	fhw=open("data.txt","a")
	num=fhw.write("this new first line written\n")
	num1=fhw.write("this new second line written\n")
	print("num:",num)
	print("num1:",num1)
	fhw.close()

	fhr=open("data.txt","r")
	data =fhr.read()
	print("After writing:")
	print(data)
	fhr.close()
	
Output:
	Before writing:
	this is first line
	you are reading the second line
	now you are dealing with third line
	num: 28
	num1: 29
	After writing:
	this is first line
	you are reading the second line
	now you are dealing with third line
	this new first line written
	this new second line written
Notepad

Note: The file 'data.txt' is opened in append mode, so the previous content of file is preserved and it contains all five lines after writing into it.

Getting current position of the file object pointer

Python provides tell() method to get current position which is pointed by file object within the file.

Syntax
//Syntax:
	file_object.tell()
CODE/PROGRAM/EXAMPLE
//Example:

	fhr=open("data.txt","r")
	cur_pos=fhr.tell()
	print(cur_pos)
	data =fhr.readline()
	print(data)

	cur_pos=fhr.tell()
	print(cur_pos)
	data =fhr.readline()
	print(data)
	fhr.close()
	
Output:
	0
	this new first line written
	29
	this new second line written
#python_write_to_file #file_writing_in_Python #python_write_to_text_file #python_read_and_write_file

(New page will open, for Comment)

Not yet commented...