Home > database >  Unexpected behaviour while outputting file in python
Unexpected behaviour while outputting file in python

Time:08-06

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

CodePudding user response:

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)

CodePudding user response:

%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
  • Related