How to Write Integers to a File

4.2/5 - (5 votes)

Problem Formulation and Solution Overview

In this article, you’ll learn how to write integers to a file in Python.

To make it more fun, we have the following running scenario:

MediTech, a pharmaceutical manufacturing company, is seeking the best way to save its drug test results. They have contacted you to provide possible solutions.

Integers to write to a file:

[32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]

πŸ’¬ Question: How would we write code to save integer(s) to a file?

We can accomplish this task by one of the following options:


Method 1: Use open()

This option shows you how to create a new file and save a single integer or list of integers to a flat-text file.

Example 1 – Single Integer

nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]
fp = open('nums_method_1a.txt', 'w')
fp.write('{}'.format(nums[3]))
fp.close()

Above, a list of integers is declared (nums). Then, a new flat-text file (nums_method_01a.txt) is created and opened in write (w) mode.

Next, the highlighted line uses the format() function to convert the single element (nums[3]) to a string and write it to the text file indicated above. Finally, fp.close() is called to close the open connection.

If successful, nums_method_01a.txt contains the following:

31651
Python open() Function -- An 80/20 Guide by Example

Example 2 – Multiple Integers

In this example, we break out of the list format and save the results as a string.

nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]
fp  = open('nums_method_1b.txt', 'w')
tmp = (','.join(str(n)for n in nums))
fp.write('{}'.format(tmp))
fp.close()

Above, a list of integers is declared (nums). Then, a new flat-text file (nums_method_01b.txt) is created and opened in write (w) mode.

Next, the join() method is called and does the following:

  • Uses the for loop to iterate through nums elements.
  • Converts each element to a string.
  • Places a separating comma (,) between each.
  • Returns a formatted string and saves it to tmp.

The contents of tmp are written to the text file indicated above. Finally, fp.close() is called to close the open connection.

If successful, nums_method_01b.txt contains the following:

32423,30902,28153,31651,36795,28939,26144,21940
Python String Methods [Ultimate Guide]

Method 2: Use NumPy

This option calls the NumPy library to save the data to a CSV. Click here for NumPy installation instructions.

import numpy as np 
nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]
nums.insert(0,'Integers')
np.savetxt('nums_method_2a.csv', nums, delimiter=" ",  fmt='% s') 

Above, the first line calls in the NumPy library. Then, a list of integers is declared (nums).

Next, let’s create a header row containing one (1) column for the CSV file and insert it at the first position of nums. The contents of nums is now:

['Integers', 32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]

Then, the np.savetext() function is called and passed the following arguments:

  • The file’s name to save the data to (nums_method_2a.csv).
  • The array containing the data. In this case, nums.
  • The delimiter – the string or character separating the columns (delimiter=" ").
  • The string format of the converted integers (fmt='% s').

If successful, nums_method_02a.csv contains the following:

Integers
32423
30902
28153
31651
36795
28939
26144
21940
NumPy Tutorial - Everything You Need to Know to Get Started

πŸ’‘Note: The delimiter is not required for this example and produces the same results with or without this argument.


Method 3: Use Pandas

This option uses the Pandas library csv to create a new file and save it to a CSV. Click here for Pandas installation instructions.

import csv
nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]
str_nums = [str(x) for x in nums]

with open('method_3a.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(str_nums)

Above, the first line calls in csv (import csv), which is available through the Pandas library. This is needed to write the data to a CSV. Then, a list of integers is declared (nums).

Before continuing, these values need to be converted to strings. A one-liner ([str(x) for x in nums]) does the trick! The results save to str_nums.

Next, the file method_3a.csv is opened in write (w) mode, assigns the newline character as an empty ('') string and creates an object (csvfile).

This object is assigned to writer and then the writer.writerow() function is called and passed the argument str_nums.

If successful, nums_method_03a.csv contains the following:

32423,30902,28153,31651,36795,28939,26144,21940

πŸ’‘Note: For this example, only one (1) row was written to the CSV so writer.writerow() was used. However, to write more than one (1) line, use writer.writerows().


Method 4: Use a One-Liner

This option uses Python’s infamous One-Liner to convert the nums list into a string and write it to a flat-text file in one fell swoop!

nums = [32423, 30902, 28153, 31651, 36795, 28939, 26144, 21940]
print(*nums, sep=",", file=open('nums_method_4a.txt', 'w'))

Above, the first line declares a list of integers (nums).

Next, the print() statement is called and does the following:

  • Reads in nums.
  • Let the print() statement know that the nums elements are separated with a comma (,) character.
  • Creates and opens the nums_method_4a.txt file in write (w) mode.
  • Saves all nums string elements to the above file.

If successful, nums_method_4a.txt contains the following:

32423,30902,28153,31651,36795,28939,26144,21940

🌟A Finxter Favorite!


Summary

These four (4) methods of writing integers to a file should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Regex Humor

Wait, forgot to escape a space. Wheeeeee[taptaptap]eeeeee. (source)