简体   繁体   English

如何在Python中读取csv文件?

[英]How to read a csv file in Python?

I need to read a csv file (named CityPop.csv ) and this is the code I have: 我需要读取一个csv文件(名为CityPop.csv ),这是我的代码:

import csv

with open ('CityPop.csv', 'r') as f:
    read_data = f.read()
    for line in f:
        record=line.strip().split(",")
print read_data

f.close()

But when I try to run it, nothing is output. 但是当我尝试运行它时,什么也没有输出。

I am not sure how to continue; 我不确定如何继续; this only leads into more advanced tasks I need to complete, which is difficult if I can't even figure this out. 这只会导致我需要完成更高级的任务,如果我什至不知道这是很难的。

Try this code 试试这个代码

import csv

    with open ('CityPop.csv', 'r') as f:
        reader = csv.reader(f, delimiter=",")
        #read_data = f.read()
        for line in reader:
            print(line)
            #record=line.strip().split(",")
    #print (read_data)

    f.close()

EDIT As Ralf said " f.close() is not necessary when using a with block" 编辑正如拉尔夫所说:“在使用with块时不需要f.close()

An easier way of reading csv files using pandas library - 使用Pandas库读取CSV文件的更简单方法-

import pandas

df = pandas.read_csv('CityPop.csv')

print(df)

or you can try modifying your code as below - 或者您可以尝试如下修改代码-

import csv

with open ('CityPop.csv', 'r') as f:

  read_data = csv.reader(f,delimiter=',')

  for row in read_data:

            print(row)

You have imported the csv module but never used it. 您已经导入了csv模块,但从未使用过它。 So try read_data = csv.reader(f) . 因此,尝试read_data = csv.reader(f)

I suggest you follow the example from the docs of the python csv module : 我建议您遵循python csv模块文档中的示例:

import csv
with open('CityPop.csv') as f:
    csv_reader = csv.reader(f, delimiter=', ')
    for row in csv_reader:
        print ', '.join(row)

Analizing your code, there are a few issues: 分析您的代码,有一些问题:

  1. you don't need to call f.close() if you use a with statement, the file will be closed automatically when exiting the with block 如果使用with语句,则无需调用f.close() ,退出with块时文件将自动关闭
  2. your print statement should go inside the with block, as the variable read_data is defined inside it 您的打印语句应该放在with块中,因为变量read_data是在其中定义的
  3. you would need to iterate read_data ( for line in read_data: ), because you already used f.read() so that iterating over f will no yield anything 您将需要迭代read_datafor line in read_data: ),因为您已经使用过f.read()因此对f迭代将不会产生任何结果
  4. you are overwriting record each time, so I don't know why you want to it that way 您每次都覆盖record ,所以我不知道您为什么要这样做
import csv

with open('CityPro.cvs') as f:
    r = csv.reader(f, delimiter=',')
    for line in r:
            print(line)
    f.close()

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

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