Python One-Liner: Write String to File

5/5 - (3 votes)
Python One-Liner: Write String to File

Problem: Given a string and a filename. How to write the string into the file with filename using only a single line of Python code?

Example: You have filename 'hello.txt' and you want to write string 'hello world!' into the file.

hi = 'hello world!'
file = 'hello.txt'

# Write hi in file

# File: 'hello.txt':
hello world!

How to achieve this? In this tutorial, you’ll learn four ways of doing it in a single line of code!

Here’s a quick overview in our interactive Python shell:

Exercise: Run the code and check the file 'hello.txt'. How many 'hello worlds!' are there in the file? Change the code so that only one 'hello world!' is in the file!

Method 1: Using the ‘With’ Statement

The most straightforward way is to use the with statement in a single line (without line break).

hi = 'hello world!'
file = 'hello.txt'

# Method 1: 'with' statement
with open(file, 'a') as f: f.write(hi)

# File: 'hello.txt':
hello world!

You use the following steps:

  • The with environment makes sure that there are no side-effects such as open files.
  • The open(file, 'a') statement opens the file with filename file and appends the text you write to the contents of the file. You can also use open(file, 'w') to overwrite the existing file content.
  • The new file returned by the open() statement is named f.
  • In the with body, you use the statement f.write(string) to write string into the file f. In our example, the string is 'hello world!'.

Of course, a prettier way to write this in two lines would be to use proper indentation:

with open(file, 'a') as f:

This is the most well-known way to write a string into a file. The big advantage is that you don’t have to close the file—the with environment does it for you! That’s why many coders consider this to be the most Pythonic way.

But not so fast!

Method 2: print() Function with File Object

Every Python coder knows the print() function. But most Python coders don’t know that the print() function also has an optional file argument. You can use any file object as the file argument to print the results into the file.

hi = 'hello world!'
file = 'hello.txt'

# Method 2: print() function
print(hi, file=open(file, 'a'))

Using the print() function is a beautiful, short, easy-to-remember, and Pythonic way to write strings into a file!

The method is clearly the most concise one and I’d recommend it to any Python coder.

It comes with only one disadvantage: you should close the file after opening it.

Well, this can also be an advantage compared to the with statement. Say, you have a big code file and you need to write stuff into a file in the beginning and at the end of the code. Using the with statement means that you must open the file twice (because it’s clearly inferior to writing your whole Python code within a single with body).

In this case, it would be even better to open the file once and pass it into a print() function call in the beginning and at the end.

πŸ’‘ 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 know that many Python coders are very rigorous about this—they’d protest against this “lazy” policy of not closing a file. In my opinion, you can and must leverage knowledge about the implementation details of a Python language. If this would be “unpythonic”, you should also not use implicit Boolean conversions like if []: print('empty') because they also require intimate knowledge of Python implementation details.

(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: Multi-Line File Writing Statement with Semicolon

Sure, you can also use a simple multi-line statement to cram everything into a single line of Python code:

hi = 'hello world!'
file = 'hello.txt'

# Method 3: multi-line statement
f = open(file, 'a'); f.write(hi); f.close()

The statement consists of three operations, separated by the semicolon:

  • open(file, 'a'): Opens and creates a file object in appending mode.
  • f.write(hi): Writes the string 'hello world!' into the file.
  • f.close(): Closes the file object.

πŸ‘‰ Recommended Tutorial: If you want to write the file to another folder, feel free to check out this tutorial on the Finxter blog.

If you don’t care about closing files (because you know what you do), you can simplify this to the following:

Method 4: Chaining open() and write()

This method is only recommended if you are sure that you don’t use the file in your code a second time (and even then, you may get away with it because you cannot even use the first file object a second time as you threw away its reference):

hi = 'hello world!'
file = 'hello.txt'

# Method 4: open() and write()
open(file, 'a').write(hi)

You create the file object and write into it using only a single line. This is the shortest and most concise way to write stuff into a file. Yes, you don’t close the file. But Python’s garbage collector will probably throw away the file object anyway because there’s no reference pointing to the file object.

If you like one-liners and you enjoyed this tutorial, have a look at my new book:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!