我正面临python csv文件中“标头”重复的问题。当我执行代码时,我得到了另一个我想要的csv文件,因此它位于正确的路径上,但问题出在其中,我在下面的结果中显示了此信息:
import csv
with open('url.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
url=row['URL']
no_dots= url.count(".")
no_per= url.count("%")
no_dash= url.count("-")
no_under= url.count("_")
no_equal= url.count("=")
no_question=url.count("?")
no_colon=url.count(":")
no_ampper=url.count("&")
no_hash=url.count("#")
no_dollar=url.count("$")
no_atrate=url.count("@")
no_exla=url.count("!")
no_star=url.count("*")
no_plus=url.count("+")
no_hiphen=url.count("-")
no_xor=url.count("^")
no_slash=url.count("/")
no_less=url.count("<")
no_greater=url.count(">")
with open('features.csv', 'a') as csvfile:
fieldnames = ['dots', 'per','dash','under','equal','question','colon','ampper','hash','dollar','atrate','exla','star',
'plus','hiphen','xor','slash','less','greater','URL']
writer = csv.DictWriter(csvfile,fieldnames=fieldnames)
writer.writeheader()
writer.writerow({'dots': no_dots, 'per': no_per,'dash':no_dash,'under':no_under,
'equal': no_equal, 'question': no_question, 'colon': no_colon , 'ampper': no_ampper, 'hash': no_hash, 'dollar': no_dollar, 'atrate': no_atrate,
'exla': no_exla, 'star': no_star , 'plus': no_plus,'hiphen': no_hiphen, 'xor': no_xor, 'slash': no_slash, 'less': no_less, 'greater': no_greater,
'URL':url}
我期望得到这样的结果:
dots per dash under equal question colon ampper hash....url
1 0 0 0 1 1 1 0 0
https://stackoverflow.com/questions/ask?guided=true
但是我得到的结果是每个URL重复重复标题,而我的数据集中有超过50000个URL ... 请帮助我的代码。预先感谢。
答案 0 :(得分:0)
import os
out_file = '/path/to/my/features.csv'
if not os.path.isfile(out_file):
writer.writeheader()
writer.writerow({'
else:
writer.writerow({'
您以“ a”附加模式打开输出文件/字典,因此请检查文件是否存在(如果不存在),则写入标题和行,如果存在,则仅写入行。 HTH