Overview
In Python, there are different strategies to create, open, close, read, write, update and delete the files. It permits the users to deal with the files, i.e., read and write, alongside numerous other file handling operations. In this article, we are going to look at the various methods to write text in a line in a file from within a Python script.
Here’s a popular question that best describes the topic of our discussion in this tutorial.
I'm used to doing print >>f, "hi there" However, it seems that print >> is getting deprecated. What is the recommended way to do the line above? source: stackoverflow
Method 1: open() + “with”:
Approach: The easiest way to write a line to file using Python is to use the built-in file method open()
along with the with
statement.
►open() Function
The open()
function is used to open a file. It returns a file object.
Syntax:
f = open(path, mode)
Parameter | Description |
---|---|
file | The name/path of the file that you want to open. |
mode | Used to define the mode in which you want to open the file in. ⦿ "r" – Read – Used to open a file for reading purpose. [If file doesn’t exist – ERROR]⦿ "a" – Append – Used to append the text you write to the file. [If file doesn’t exist – Creates the File] ⦿ "w" – Write – Used to open a file for writing purpose. [If file doesn’t exist – Creates the File] ⦿ "x" – Create – Simply creates the file. [If file exists – ERROR] |
Example: In the following code we will open a file named ‘demo.txt
‘ and write two lines of text in it.
lines = ['Hello', 'Welcome to Finxter!'] # Opening the file in write mode f = open("demo.txt", "w") for line in lines: # Writing a new word into the file f.write(line) f.write("\n") # Closing the file f.close()
Output:
Discussion:
- We used the
f.write('\n')
to add a new line after each line because thef.write()
method does not add a newline character (‘\n’) automatically at the end of the line. Hence, you have to explicitly add ‘\n’ character. - The
f.close()
function is used to close the file access. It is always better to usef.close()
to close the file after completing all the operations. - Note: The
open()
function will create a new file in casedemo.txt
does not exist.
►with Statement
The with
statement makes sure that there are no side-effects such as open files. Therefore, when the with
statement is used, you do not need to use f.close()
as it ensures proper acquisition.
Example:
lines = ['Hello', 'Welcome to Finxter!'] # Opening the file in write mode with open('demo.txt', 'w') as f: for line in lines: f.write(line) f.write('\n')
Method 2: Using The Print function()
Well most of us began with the print “Hello World” code in Python. That is when we first came across the print()
function in Python. But as a novice we did not know the true potential of the print() function. Yes! There’s more to it. You can use the print statement along an optional file argument. You can use any file object as the file
argument to print the results into the file.
Example:
line = 'hello world!' file = 'hello.txt' # Method 2: print() function print(line, file=open(file, 'a'))
Output:
Discussion: It is generally advised to close a file after you are done with it. Hence this is a disadvantage of using the print()
function to write a line in a file. Strictly speaking, you don’t even need to close the file if you know what you’re doing. Python closes all files automatically if the script terminates.
(I’m aware of the standard arguments for closing files but I don’t think they are very “hard” arguments for doing that—they are just “safe” and easy to recommend. Most people stating them do not close files all the time themselves. ?)
Method 3: Using writelines()
Python has the writelines()
method that is used to write all the lines simultaneously to a file. This method accepts a list of words as input and further writes it to the file after opening it using the write
or append
mode. This method accepts any iterable object so you can also pass a tuple or a set of strings easily.
Example:
# List of words words = ['Hello', 'Welcome to Finxter!'] # Opening the file in write mode with open('demo.txt', 'w') as f: f.writelines(words)
Output:
Now let’s look at the example of how to use writelines() method with the append mode:
lines = ['Correct way to write line in a file', 'Thank you'] # Opening the file in append mode with open('demo.txt', 'a') as f: f.writelines('\n' .join(lines))
Output:
Method 4: Using The insert() Function
You can also use the insert()
function to write to a file in Python. It accepts two parameters where the first parameter specifies the position at which you want to insert the content and the second parameter specifies the value that must be inserted into the list.
Approach:
- First, you have to open the file in read (
r
) mode. Then use the readlines method to read all the lines of the file specified. Thereadlines()
method is used to return a list of all the lines in the file. - Then, use the
insert()
method to add more content at the position specified. Now, to write all the contents of the given file you have to use the.join()
function. This function will convert the list into a string. Now, you can easily write into the file.
Example: Let’s consider that we have a file as shown below and we want to insert a line at the beginning.
with open('demo.txt', 'r') as f: words = f.readlines() words.insert(0, 'Inserting a line in the File.\n') with open('demo.txt', 'w') as f: words = f.writelines(words)
Output:
Conclusion
Here, we discussed numerous ways of writing a line in a file using Python. I hope this tutorial answered your queries. However, if you want to dive deeper into file operations/ modifying files in Python, then I highly recommend you to have a look at this article – “Modify a Text File in Python” wherein numerous ways of modifying a file in Python have been discussed.
With that, we come to the end of this article, and I hope you enjoyed this tutorial! Please stay tuned and subscribe for more interesting articles and discussions.