Unexpected behaviour while outputting file in python

I have the following code:

import csv
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

for x in range(10, 11): 
    df.to_csv("file_%x.csv" % x, index=False)

Instead of returning file_10.csv, the code returns file_a.csv. Why is this happening? I checked the value of x in the loop and it is indeed 10, so why is it being converted to ‘a’?

>Solution :

The old %-style string formatting uses largely C-derived directives. %x instructs the formatter to print the number in hexadecimal, so 10 is a. Use %s to stringify in the default way.

df.to_csv("file_%s.csv" % x, index=False)

or, better, use f-strings if you’re on Python 3.6+ (which you should be)

df.to_csv(f"file_{x}.csv", index=False)

Leave a Reply