- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python float() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python ascii() Function
- Python pow() Function
- Python type() Function
- Python List Functions
- Python list() Function
- Python insert() Function
- Python append() Function
- Python extend() Function
- Python pop() Function
- Python remove() Function
- Python reverse() Function
- Python sort() Function
- Python sorted() Function
- Python Dictionary Functions
- Python dict() Function
- Python update() Function
- Python get() Function
- Python keys() Function
- Python setdefault() Function
- Python fromkeys() Function
- Python items() Function
- Python popitem() Function
- Python Tuple Function
- Python tuple() Function
- Python Set Functions
- Python set() Function
- Python frozenset() Function
- Python String Functions
- Python split() Function
- Python join() Function
- Python format() Function
- Python replace() Function
- Python Iterator Functions
- Python iter() Function
- Python min() Function
- Python max() Function
- Python sum() Function
- Python count() Function
- Python index() Function
- Python copy() Function
- Python clear() Function
- Python next() Function
- Python filter() Function
- Python enumerate() Function
- Python zip() Function
- Python reversed() Function
- Python Number Functions
- Python abs() Function
- Python bin() Function
- Python oct() Function
- Python hex() Function
- Python round() Function
- Python divmod() Function
- Python complex() Function
- Python File Handling Functions
- Python open() Function
- Python read() Function
- Python readable() Function
- Python readline() Function
- Python readlines() Function
- Python write() Function
- Python writable() Function
- Python writelines() Function
- Python close() Function
- Python seek() Function
- Python tell() Function
- Python flush() Function
- Python fileno() Function
- Python truncate() Function
- Python Class Functions
- Python object() Function
- Python property() Function
- Python getattr() Function
- Python setattr() Function
- Python hasattr() Function
- Python delattr() Function
- Python classmethod() Function
- Python staticmethod() Function
- Python issubclass() Function
- Python super() Function
- Python Misc Functions
- Python all() Function
- Python any() Function
- Python isatty() Function
- Python bool() Function
- Python callable() Function
- Python globals() Function
- Python locals() Function
- Python dir() Function
- Python id() Function
- Python isinstance() Function
- Python map() Function
- Python repr() Function
- Python slice() Function
- Python vars() Function
- Python Advance Functions
- Python help() Function
- Python hash() Function
- Python breakpoint() Function
- Python bytes() Function
- Python bytearray() Function
- Python memoryview() Function
- Python compile() Function
- Python eval() Function
- Python exec() Function
- Python Tutorial
- Python Tutorial
- Python Examples
- Python Examples
Python write() Function
The write() function in Python used to write content (text) in a file. The function is used either to write or to append the data to the file depending on its opening mode.
Note: The w mode is for writing, whereas the a mode is for appending.
Python write() Syntax
The syntax to use write() function in a Python program is:
fo.write(string_to_write)
where fo indicates to the file object or handler, and string_to_write is the string or text that has to be written in the file whose handler is fo.
Python write() Example
The program given below uses write() function to write some texts say Hey! My name is Michael Smith to a file say fresherearth.txt. Before writing to the file, we need to open the file, so here I've used w opening mode.
Because I've used w opening mode, therefore if the file fresherearth.txt is not available in the current directory, then the file automatically gets created and the content gets written in it. Otherwise, if file is available, then the content gets overwritten or previous content gets deleted and this new content gets written. Let's see how.
fo = open("fresherearth.txt", "w") fo.write("Hey! My name is Michael Smith") print("The content written in the file.") fo.close()
If you execute this program, then the output produced will be:
Now if you open the current directory, then this file with same content will be available. Here is the snapshot of the file that is created using the above program in my case:
Now let's create another program, that demonstrates all about write() function in single Python program. This program is created, so that, the name of file gets received by user, at run-time of the program.
print("Enter File's Name: ", end="") filename = input() print("\n1. Write Content.") print("2. Append Content.") print("Enter Your Choice (1 or 2): ", end="") choice = int(input()) if choice == 1: fo = open(filename, "w+") print("\nEnter the content to write: ", end="") content = input() fo.write(content) print("\n----Content of File----") fo.seek(0) print(fo.read()) fo.close() elif choice == 2: fo = open(filename, "a+") print("\nEnter the content to append: ", end="") content = input() fo.write("\n") fo.write(content) print("\n----Content of File----") fo.seek(0) print(fo.read()) fo.close() else: print("\nInvalid Input!")
Here is its sample run with user input fresherearth.txt as name of file, 2 as choice, and This is a tutorial on write() Function. as content:
Note: The end= parameter, in above program, used to skip automatic insertion of a newline using the default behavior of print() function.
The following statement:
fo.seek(0)
is used to move the file handler at the beginning of the file to read all the content from start to end. To learn in detail about seek(), refer to its separate tutorial.
And the statement:
fo.write("\n")
is used to append the content from newline.
« Previous Function Next Function »