Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除Python中的csv行_Python_Csv - Fatal编程技术网

删除Python中的csv行

删除Python中的csv行,python,csv,Python,Csv,脚本从csv文件中获取链接,并从网页中获取一些信息。有些链接不起作用,脚本会出错。我包含了try/except,但这会弄乱我的输出,因为我需要与原始文件中相同数量的输出行 for row in reader: try: url = row[4] req=urllib2.Request(url) tree = lxml.html.fromstring(urllib2.urlopen(req).read()) except:

脚本从csv文件中获取链接,并从网页中获取一些信息。有些链接不起作用,脚本会出错。我包含了try/except,但这会弄乱我的输出,因为我需要与原始文件中相同数量的输出行

for row in reader:
    try:
        url = row[4]
        req=urllib2.Request(url)
        tree = lxml.html.fromstring(urllib2.urlopen(req).read())
    except:
        continue
有没有办法从有错误链接的csv文件中删除该行? 比如:

for row in reader:
    try:
        url = row[4]
        req=urllib2.Request(url)
        tree = lxml.html.fromstring(urllib2.urlopen(req).read())
    except:
        continue
        DELETE_THE_ROW

如果一切顺利,为什么不将好的行写入另一个文件

writer = csv.writer(out_file_handle)
for row in reader:
    try:
        url = row[4]
        req=urllib2.Request(url)
        tree = lxml.html.fromstring(urllib2.urlopen(req).read())
    except:
        continue
    else:
       writer.writerow(row)

最好的方法是创建一个新的csv文件,并继续只写入链接有效的行

f = open('another_csv.csv','w+')
for row in reader:
    try:
       url = row[4]
       req=urllib2.Request(url)
       tree = lxml.html.fromstring(urllib2.urlopen(req).read())
       print >>f,','.join(row)
    except:
       #can log the faulty links in another file
       continue
f.close()

您可以将新的csv重命名为原始csv,也可以同时保留两者。

这是可行的,但会带来一些麻烦。由于原始文件中有逗号(如文章标题中的逗号),因此带有“,”分隔符的新文件非常混乱。有没有办法避免这个问题?给你:
print>>f'“+”,“'.join(row)+'”
或者你可以直接使用@Yann中提到的csv.writer。它将只引用那些有逗号的字段。对所有字段使用引号也会增加文件大小。为什么
“需要与原始文件中相同数量的输出行”