简体   繁体   English

在Python中使用变量的问题

[英]Trouble with using a variable in Python

I am a beginner in Python and I know this question is pretty basic but I can't seem to find the solution from Googling. 我是Python的初学者,我知道这个问题很基本,但是我似乎无法在Googling上找到解决方案。

I am writing a simple scraping script in Python and I am using BeautifulSoup for parsing. 我正在用Python编写一个简单的抓取脚本,并且正在使用BeautifulSoup进行解析。 I am just stuck in using a variable to set the filename of my CSV write functions. 我只是停留在使用变量来设置CSV写入函数的文件名中。 say I have a variable called "category", how can I set that as the name of the CSV file? 说我有一个名为“ category”的变量,如何将其设置为CSV文件的名称?

category = "student"

with open('%category.csv', 'a') as csv_file:  
   writer = csv.writer(csv_file)
   writer.writerow([cname, caddress, ccontact])

Try this: 尝试这个:

with open(category + '.csv', 'a') as csv_file:  

You do not substitute the variable like that. 您不能像这样替换变量。 Read a basic book. 阅读基础书籍。

Try this instead: 尝试以下方法:

with open('%s.csv' % category, 'a') as csv_file:  

See this informative article for more on string formatting in Python. 有关Python中字符串格式的更多信息 ,请参见这篇信息丰富的文章

Use format() like this: 像这样使用format()

with open('{}.csv'.format(category), 'a') as csv_file:

Output: 输出:

>>> category = 'my_file'
>>> '{}.csv'.format(category)
'my_file.csv'

This task can be achieved by many ways and few of which are listed below : 此任务可以通过许多方法来实现,下面列出了几种方法:

  1. String Concatenation . 字符串串联。

     category = "student" with open(category + '.csv', 'a') as csv_file: 
  2. String Formatting 字符串格式化

      with open('%s.csv' % category, 'a') as csv_file: 
  3. Using format() function 使用format()函数

     with open('{}.csv'.format(category), 'a') as csv_file: 

I hope these all will work fine for you. 希望所有这些对您都可以。

Best One is :- 最好的是:

category = "student.csv" 
with open(category, 'a') as csv_file:

The last one is simplest one , to change the name of file just change the value of variable. 最后一个是最简单的一个,要更改文件名,只需更改变量的值即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM