• Skip to secondary menu
  • Skip to main content
  • Skip to primary sidebar

Python and R Tips

Learn Data Science with Python and R

  • Home
  • Python
  • Pandas
    • Pandas 101
  • tidyverse
    • tidyverse 101
  • R
  • Linux
  • Conferences
  • Python Books
  • About
    • Privacy Policy
You are here: Home / Python / 3 Ways to Write Text to a File in Python

3 Ways to Write Text to a File in Python

September 25, 2012 by cmdlinetips

If you are interested in writing text to a file in Python, there is probably many ways to do it. Here is three ways to write text to a output file in Python.  The first step in writing to a file is create the file object by using the built-in Python command “open”. To create and write to a new file, use open with “w” option. The “w” option will delete any previous existing file and create a new file to write.
# open a (new) file to write
outF = open("myOutFile.txt", "w")

If you want to append to an existing file, then use open statement with “a” option. In append mode, Python will create the file if it does not exist.

# open a file to append
outF = open("myOutFile.txt", "a")

Once you have created the file object in write/append mode, you can write text in multiple ways. Let us say we have the text that we want to write is in a list “textList”.

textList = ["One", "Two", "Three", "Four", "Five"]

We can write this list to a file either line by line or write all lines at once.

Writing One Line at a Time to a File in Python Using write()


Let us create new file by creating the file object “outF” using “w” option as before. To write line by line, we loop through the textList and get each element and write it to the file.

outF = open("myOutFile.txt", "w")
for line in textList:
  # write line to output file
  outF.write(line)
  outF.write("\n")
outF.close()

Note that the elements in the “textList” does not have a new line character “\n”. Therefore, we added that while writing to the file. Otherwise, all five elements will be in a single line in the output file. Also note outF.close() at the end. close() method closes the access to the file. It is a good practice to use the close() method to close a file, once we are done with a file.

Writing One Line at a Time to a File in Python Using “print”

Another way to write one line at a time to a file in Python is to use the print statement. Instead of printing a statement to the scree, we redirect to the output file object.

outF = open("myOutFile.txt", "w")
for line in textList:
  print >>outF, line
outF.close()

writelines(): Writing All The Lines at a Time to a File in Python

writelines command to write all lines to a file
python writelines to write all lines

Python also has a method that can write all lines at the same time to a file. Python’s “writelines()” method takes a list of lines as input and writes to a file object that is open with write/append access. For example to write our list of all line “all_lines”, using “writelines().

outF = open("myOutFile.txt", "w")
outF.writelines(all_lines)
outF.close()

We can also make our lives easier without writing file.close() statement by using with statement to write to a file. For example,

with open(out_filename, 'w') as out_file:
     .. 
     .. 
     .. parsed_line
     out_file.write(parsed_line)

If you are interested in reading from a text file, check Three ways to read a text file line by line in python.

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Related posts:

Default Thumbnail3 Ways to Read A Text File Line by Line in Python “with” statement in Python to Open a file Default ThumbnailHow to read entire text file in Python? Default Thumbnail3 Ways to Read a File and Skip Initial Comments in Python

Filed Under: Python, Python Tips, Python Write Text To A File Tagged With: Python, Python print, Python Tips, Python Write Text To A File, Python write(), Python writelines()

Primary Sidebar

Subscribe to Python and R Tips and Learn Data Science

Learn Pandas in Python and Tidyverse in R

Tags

Altair Basic NumPy Book Review Data Science Data Science Books Data Science Resources Data Science Roundup Data Visualization Dimensionality Reduction Dropbox Dropbox Free Space Dropbox Tips Emacs Emacs Tips ggplot2 Linux Commands Linux Tips Mac Os X Tips Maximum Likelihood Estimation in R MLE in R NumPy Pandas Pandas 101 Pandas Dataframe Pandas Data Frame pandas groupby() Pandas select columns Pandas select_dtypes Python Python 3 Python Boxplot Python Tips R rstats R Tips Seaborn Seaborn Boxplot Seaborn Catplot Shell Scripting Sparse Matrix in Python tidy evaluation tidyverse tidyverse 101 Vim Vim Tips

RSS RSS

  • How to convert row names to a column in Pandas
  • How to resize an image with PyTorch
  • Fashion-MNIST data from PyTorch
  • Pandas case_when() with multiple examples
  • An Introduction to Statistical Learning: with Applications in Python Is Here
  • 10 Tips to customize ggplot2 title text
  • 8 Plot types with Matplotlib in Python
  • PCA on S&P 500 Stock Return Data
  • Linear Regression with Matrix Decomposition Methods
  • Numpy’s random choice() function

Copyright © 2025 · Lifestyle Pro on Genesis Framework · WordPress · Log in

Go to mobile version