首页 > 解决方案 > CSV 文件:在 Python 中打开并仅打印链接

问题描述

我有 CSV 文件,其中一些链接存储在其中一列中。我只想阅读链接并将它们打印出来。我尝试使用以下代码,但没有输出。

import csv
filename ='abc.csv'
with open(filename,'rb') as f:
    reader = csv.reader(f)
    for row in reader:
     for item in row:
         if item.startswith('http'):
             print(item)

标签: python-3.xcsv

解决方案


import csv

with open ('abc.csv','r') as csv_file:
    csv_reader = csv.reader(csv_file)

    for line in csv_reader:
        if line[0].startswith('http'):
            print(line)

如果您想确保该行以例如“http”开头,您应该编写:

line[0].startswith("http") 因为行列表的第一个元素将是一个字符串。


推荐阅读