No Result
View All Result
DevRescue
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us
DevRescue
Home Blog Python

Python writelines With Examples

by Khaleel O.
September 6, 2021
in Python
Reading Time: 4 mins read
A A
Python writelines
Python writelines

We can use the Python writelines method to write a list of lines to a stream. A stream can be text, binary or raw. In this example we will use writelines to write some lines to a text stream. Here is some code:

f = open("file1.txt", "w")
f.writelines(["---Line1---", "---Line2---"])
f.close()

Let’s explain what is happening here:

  1. The open() method opens a file and returns a corresponding file object f.
  2. We supply two arguments to the open() method: a filename (file1.txt) in the local path and a mode which is “w” for write in this case. The mode “w” opens the file for writing but truncates it first.
  3. The writelines() method accepts a list of lines (Line1 and Line2). We supply a list of 2 lines in this case. These lines are written to our file object file1.txt. Note that line separators are not added.
  4. close() flushes and closes the stream. Once the file is closed no further operations are possible. The file can now be found on the local storage of the OS in the same folder as your python script.

When the above code executes there will be a new file on the filesystem. We can read the lines from this new file we just wrote to:

f = open("file1.txt", "r")
print(f.read())
f.close()

#Output
#---Line1------Line2---

Let’s explain what is happening here:

  1. We use the open() method and we supply the file name (file1.txt) and the mode which is “r” in this case. The mode “r” opens the file for reading. The file object f is returned.
  2. The read() method reads and returns data from the file object until EOF.
  3. close() flushes and closes the stream.

The output from reading the file may not be as expected. Ideally, we want each line of a different line. Recall that with writelines line separators are not added by default. We have to add our own line separators:

f = open("file1.txt", "w")
f.writelines(["---Line1---\n", "---Line2---\n"])
f.close()

f = open("file1.txt", "r")
print(f.read())
f.close()

#output
#---Line1---
#---Line2---

Note that now we have each line of our list inserted into the file on a different line. All we needed to do was add the new line \n character to each line in the list supplied to the writelines method.

Also, recall that the mode “w” opens the file for writing but also truncates its contents. By using the mode “a” in the open() method we can open our file for appending instead.

Mode “a” opens the file for writing, appending new lines to the end of the file if it exists:

f = open("file1.txt", "a")
f.writelines(["---Line3---\n", "---Line4---\n"])
f.close()

f = open("file1.txt", "r")
print(f.read())
f.close()

#Outputs
#---Line1---
#---Line2---
#---Line3---
#---Line4---

We can actually do the same operation with writelines using a list comprehension:

lines = ['---NewLine---','---NewLine---','---NewLine---']
with open('file2.txt', 'a') as f:
    f.writelines(f"{l}\n" for l in lines)

f = open("file2.txt", "r")
print(f.read())
f.close()

#output
#---NewLine---
#---NewLine---
#---NewLine---

Finally, as an alternative to writing a file on disk we can write a text stream to an in-memory text buffer.

import io

output = io.StringIO()
output.writelines(['Line1\n','Line2\n'])

contents = output.getvalue()

print(contents)


output.close()

#output
#Line1
#Line2

Let’s explain what is happening here:

  1. Import the library io.
  2. The StringIO() method returns a text buffer output.
  3. The method writelines allows us to write a list of lines to our in-memory buffer.
  4. The getvalue() method retrieves the contents of the buffer which we can print.
  5. The close() method discards the text buffer.

Find the full source code HERE. Thanks for reading. 👌👌👌

Tags: fileswritelines
Previous Post

Add and Subtract Vectors In Python

Next Post

Python rstrip lstrip

Khaleel O.

Khaleel O.

I love to share, educate and help developers. I have 14+ years experience in IT. Currently transitioning from Systems Administration to DevOps. Avid reader, intellectual and dreamer. Enter Freely, Go safely, And leave something of the happiness you bring.

Related Posts

Python

Python Fibonacci Recursive Solution

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Fibonacci Recursive Solution. Let's go! 🔥🔥🔥 The Fibonacci sequence is a series of numbers in which...

Read moreDetails
Python

Python Slice String List Tuple

by Khaleel O.
January 16, 2024
0
0

Let's do a Python Slice string list tuple how-to tutorial. Let's go! 🔥🔥🔥 In Python, a slice is a feature...

Read moreDetails
Python

Python Blowfish Encryption Example

by Khaleel O.
January 14, 2024
0
0

Let's do a Python Blowfish Encryption example. Let's go! 🔥 🔥 Blowfish is a symmetric-key block cipher algorithm designed for...

Read moreDetails
Python

Python Deque Methods

by Khaleel O.
January 14, 2024
0
0

In this post we'll list Python Deque Methods. Ready? Let's go! 🔥🔥🔥 A deque (double-ended queue) in Python is a...

Read moreDetails

DevRescue © 2021 All Rights Reserved. Privacy Policy. Cookie Policy

Manage your privacy

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
Manage your privacy
To provide the best experiences, DevRescue.com will use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Statistics

Marketing

Features
Always active

Always active
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
Manage options
  • {title}
  • {title}
  • {title}
No Result
View All Result
  • Home
  • Python
  • Lists
  • Movies
  • Finance
  • Opinion
  • About
  • Contact Us

DevRescue © 2022 All Rights Reserved Privacy Policy