Kar
Kar

Reputation: 164

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

Upvotes: 1

Views: 46

Answers (2)

Silvio Mayolo
Silvio Mayolo

Reputation: 70287

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)

Upvotes: 4

killruana
killruana

Reputation: 178

%x converts the value to hexadecimal. What you want is %d.

>>> for i in range(16):
...     print("%d %x" % (i, i))
...
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 a
11 b
12 c
13 d
14 e
15 f

Upvotes: 2

Related Questions