Write File in Python | File Handling in Python Programming

Write File: Writing to a file is a type of operation that we perform in our file. One thing is common everywhere, that is opening file. Before performing any operation on file, opening and closing of file is mandatory for successful execution of task. There are two possibilities while writing to a file ie.


(i). If file abc.txt already existing and have some data written in the file and we are writing data to the same file abc.txt. Then in that case, the data written in the file is overridden with the new data.

(ii). If file is not existing in the system, then it will first create new file with the given name. And then perform the write operation. We can perform write operation on file using two functions or methods.


There are two ways to write a file in Python
Using write()
2). Using writelines()

(i). write(): The very first method used for writing to file is write() method. It takes ‘string’ value as argument and write it to the file. For breaking line we to have use ‘\n’ character to the end of the string. Numeric values should be first converted to string using str() method or we can write numeric values inside double quote(” “) also.

Note:  ‘\n’ is used to break the string. ie. (“www.pythonlobby\n.com”)
Output: www.pythonlobby

Example 1: 


Data written to Abc.txt file

(ii). writelines(): Writelines() method is used to write data in sequence or we can say that to write sequential data types in file ie. (string, tuples and list etc.).

Example 2:

f = open("Abc.txt",'w')
data = ['I\n','Love\n','PythonLobby\n','Tutorials\n']
    print("File Written Successfully")



writelines-in-pythonImportant Points:
File access mode ‘w’ is used for writing data in a file.
2). Always call close() function after performing operation on file to commit changes.
3). Before creating a file, always check that the file with the same name is already existing or not to secure the data loss (overridden problem if file with same name already existing).