简体   繁体   English

在Python中从csv文件中打印选定的列

[英]Printing selected columns from a csv file in Python

I have some code here: 我在这里有一些代码:

with open("dsasa.csv", 'rb') as csvfile:
content = csv.reader(csvfile, delimiter='|')
for row in content:
    print row```

I would like to print columns 2, 3, 4 from the csv file in the following format: 我想以以下格式从csv文件中打印第2、3、4列:

4556 | 432432898904 | Joseph Henry
4544 | 54522238904 | Mark Mulligan

I have two issues which I am encountering. 我遇到两个问题。 One is that the delimiter pipe (|) is not appearing between the columns. 一种是分隔符(|)没有出现在列之间。 The second issue is that I cannot print the specific columns I want by doing the manual way, ie. 第二个问题是我无法通过手动方式打印想要的特定列。 print row[2], row[3], row[4]

I looked at online info and tried a few different solutions but I can't seem to find the route to get this to work. 我查看了在线信息,并尝试了几种不同的解决方案,但我似乎找不到使它起作用的方法。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks! 谢谢!

Try this: 尝试这个:

with open("dsasa.csv", 'rb') as csvfile:
    content = csv.reader(csvfile)
    for row in content:
        print "|".join([row[2],row[3],row[4]])

The delimiter argument within csv.reader refers to the input file not the output. csv.readerdelimiter参数引用输入文件而不是输出。

What does appear between the columns as the delimiter? 在列之间作为分隔符会显示什么? Are you sure it is '|' 您确定它是“ |” and not a comma? 而不是逗号? I am guessing because you do not have the correct delimiter you cannot use print row[2], row[3], row[4]. 我猜是因为您没有正确的定界符,所以无法使用print row [2],row [3],row [4]。 Can you post a line of the CSV? 您可以发布CSV行吗?

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

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