To write an integer to a file, you just have to open a file in write mode, convert the int to a string with str(), and use the write() function.

integer = 1

with open("example.txt", "w") as f:
    f.write(str(integer))

If you want to add an integer to an existing file and append to the file, then you need to open the file in append mode.

integer = 1

with open("example.txt", "a") as f:
    f.write(str(integer))

When working with files in Python, the ability to create new files or modify existing files easily is important.

One such case is if you want to write an integer to a file.

To write an integer to a file, it is easy – you just have to open a file in write mode, convert the int to a string with str(), and use the write() function.

This is the same as if you wanted to write a variable to a file with the only difference being that you have to convert the int to a string.

Below is a simple example of how you can write an integer to a file using Python.

integer = 1

with open("example.txt", "w") as f:
    f.write(str(integer))

Append Variable to File Using Python

If you want to append an integer to a file, then you should open the file in append mode.

Below is an example showing you how to append an integer to a file in Python.

integer = 1

with open("example.txt", "a") as f:
    f.write(str(integer))

How to Write Multiple Int Values to a File Using Python

If you want to write multiple integer varaibles to a file using Python, you can build a string and then pass it to write().

For example, if you had multiple ints and wanted to print each one on it’s own line, then you could do the following in Python.

int1= 1
int2 = 2
int3 = 3

with open("example.txt", "w") as f:
    f.write(str(int1) + "n")
    f.write(str(int2) + "n")
    f.write(str(int3) + "n")

If you wanted to create a file where the integers were comma delimited, then you could print them all on one line and join them with a comma.

int1= 1
int2 = 2
int3 = 3

with open("example.txt", "w") as f:
    f.write(",".join([str(int1), str(int2), str(int3)]))

Hopefully this article has been useful for you to learn how to write an int to a file in Python.

Categorized in:

Python,

Last Update: February 26, 2024