-1

Not sure if the tittle is 100% correct, please correct me if im wrong

I have a small python script as follows

x = 0 #counter


with open('products(x).csv', 'w') as csvfile:

I'm trying to make it output

product0.csv

I have a loop set up the increases the value of x

x += 1

So what I'm hoping is it will create product0.csv product1.csv product2.csv

Etc, etc.

I have tried

with open('products'(x)'.csv', 'w') as csvfile:

And I just recieve an error

  File "web.py", line 30
    with open('products'(x)'.csv', 'w') as csvfile:
                                ^ 
J...S
  • 5,079
  • 1
  • 20
  • 35
Mic
  • 331
  • 1
  • 2
  • 14
  • What is the type of `products`? where is it defined? – Hagai Dec 19 '18 at 07:10
  • products is just the first part of the name of the csv file i want to output. its nothing related to my python code. – Mic Dec 19 '18 at 07:11

4 Answers4

2

Use this

with open('products('+str(x)+').csv', 'w') as csvfile:
nishant
  • 2,526
  • 1
  • 13
  • 19
  • Im getting this error File "web.py", line 30, in with open('product_scrapped/products('+x+').csv', 'w') as csvfile: TypeError: can only concatenate str (not "int") to str – Mic Dec 19 '18 at 07:13
  • @Mic updated use it – nishant Dec 19 '18 at 07:14
2
with open('products({}).csv'.format(x), 'w') as csvfile:
        ...
P.hunter
  • 1,345
  • 2
  • 21
  • 45
1

String formatting should do the trick:

x = 0
filename = 'product{}.csv'.format(x)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
1

Try

x = 0 #counter        
with open('products'+str(x)+'.csv', 'w') as csvfile:

instead of

x = 0 #counter        
with open('products(x).csv', 'w') as csvfile:

because x is an integer. You first need to convert it to string with str() and then concatenate using the + operator.

Another way is to use format() as in

with open('products{}.csv'.format(x), 'w')
J...S
  • 5,079
  • 1
  • 20
  • 35