Writing text Files using Print function !

Abin Isaac
2 min readSep 29, 2021
babywriting.jpg (700×420) (netdna-cdn.com)

Most of the people start their python journey using print(). Print function seems to be simple and easy-go thing where whatever you put in Strings gets printed !

But print function is not that simple as we can even use it for file handling and other things also.

Print Function Syntax

print(object(s), sep=separator, end=end, file=file, flush=flush)

We will be focusing on first 4 arguments Object, sep, end and file.

  1. Objects

In python everything is an object and print() allow any number and any type of objects and prints the value depending on the arguments. It will be converted to string before printing.

print( “Learning print function”, 2, 2.789, 0+0J )OUTPUTLearning print function 2 2.789 0j

2. Seperator

In print() there is a default seperator and it is empty space. We can change it as per our wish. Default value of sep is “”

print( "Learning","print","function" ) # sep=""print( “Learning”, “print”, “function” , sep=”-” )OUTPUTLearning print function
Learning-print-function

Here in the first print the sperator is taking space by default. In the second print we explicitly mentioned our sep argument to see a different output.

3. End

In python print function default value of end is the new line character.

print(“first”) 
print()
print(“second”)
print("Learning", end = ' something ')
print("with print")
OUTPUTfirstsecond
Learning something with print

Here we see that an empty print() creates a blank line. That's because in python every print function by default has a new line argument at the end. We can easily change this as per our need.

4. File

sourceFile = open(‘my_file.txt’, ‘w’)print(‘Pretty cool, huh!’, file = sourceFile)sourceFile.close()

The first line creates a text file names my_file in write mode. After this we can start writing using our print function easily. The file location will depend on your editor, so search in that area where your editor saves file.

Thats all !

Happy learning !!

--

--