【问题标题】:Python, Putting x = 0 into a '' bracket [duplicate]Python,将x = 0放入''括号[重复]
【发布时间】:2019-05-19 15:33:17
【问题描述】:

不确定标题是否100%正确,如有错误请指正

我有一个小的python脚本如下

x = 0 #counter


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

我正在尝试让它输出

product0.csv

我有一个循环设置增加x的值

x += 1

所以我希望它会创造 产品0.csv 产品1.csv product2.csv

等等等等

我试过了

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

我只是收到一个错误

  File "web.py", line 30
    with open('products'(x)'.csv', 'w') as csvfile:
                                ^ 

【问题讨论】:

  • products的类型是什么?它是在哪里定义的?
  • products 只是我要输出的 csv 文件名称的第一部分。它与我的 python 代码无关。

标签: python csv selenium


【解决方案1】:

使用这个

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

【讨论】:

  • 我在 中收到此错误文件“web.py”,第 30 行,其中 open('product_scrapped/products('+x+').csv', 'w') as csvfile: TypeError:只能将str(不是“int”)连接到str
  • @Mic 更新使用它
【解决方案2】:

试试

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

而不是

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

因为x 是一个整数。您首先需要使用str() 将其转换为字符串,然后使用+ 运算符进行连接。

另一种方法是使用format()

with open('products{}.csv'.format(x), 'w')

【讨论】:

    【解决方案3】:

    字符串格式应该可以解决问题:

    x = 0
    filename = 'product{}.csv'.format(x)
    

    【讨论】:

      【解决方案4】:
      with open('products({}).csv'.format(x), 'w') as csvfile:
              ...
      

      【讨论】:

        猜你喜欢
        • 2021-11-06
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 1970-01-01
        • 2017-01-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多