Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading