[python] Casting an int to a string in Python

I want to be able to generate a number of text files with the names fileX.txt where X is some integer:

for i in range(key):
    filename = "ME" + i + ".txt" //Error here! Can't concat a string and int
    filenum = filename
    filenum = open(filename , 'w')  

Does anyone else know how to do the filename = "ME" + i part so I get a list of files with the names: "ME0.txt" , "ME1.txt" , "ME2.txt" , and etc

This question is related to python string integer concatenation

The answer is


For Python versions prior to 2.6, use the string formatting operator %:

filename = "ME%d.txt" % i

For 2.6 and later, use the str.format() method:

filename = "ME{0}.txt".format(i)

Though the first example still works in 2.6, the second one is preferred.

If you have more than 10 files to name this way, you might want to add leading zeros so that the files are ordered correctly in directory listings:

filename = "ME%02d.txt" % i
filename = "ME{0:02d}.txt".format(i)

This will produce file names like ME00.txt to ME99.txt. For more digits, replace the 2 in the examples with a higher number (eg, ME{0:03d}.txt).


Either:

"ME" + str(i)

Or:

"ME%d" % i

The second one is usually preferred, especially if you want to build a string from several tokens.


You can use str() to cast it, or formatters:

"ME%d.txt" % (num,)

Here answer for your code as whole:

key =10

files = ("ME%i.txt" % i for i in range(key))

#opening
files = [ open(filename, 'w') for filename in files]

# processing
for i, file in zip(range(key),files):
    file.write(str(i))
# closing
for openfile in files:
    openfile.close()

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to concatenation

Pandas Merging 101 What does ${} (dollar sign and curly braces) mean in a string in Javascript? Concatenate two NumPy arrays vertically Import multiple csv files into pandas and concatenate into one DataFrame How to concatenate columns in a Postgres SELECT? Concatenate string with field value in MySQL Most efficient way to concatenate strings in JavaScript? How to force a line break on a Javascript concatenated string? How to concatenate two IEnumerable<T> into a new IEnumerable<T>? How to concat two ArrayLists?