简体   繁体   English

逐行读取CSV文件python

[英]Read CSV file line-by-line python

I have a .csv file I am trying to read, but I'm having trouble.我有一个要读取的 .csv 文件,但遇到了问题。 Please forgive me as this is a very remedial question:请原谅我,这是一个非常补救的问题:

I'm trying to read a file line-by-line with the following:我正在尝试使用以下内容逐行读取文件:

with open('Book8.csv') as fp:
for line in fp:
    print line

If I do this I print the whole file.如果我这样做,我会打印整个文件。 like so:像这样:

1,2,3 1,2,3

4,5,6 4,5,6

7,8,9 7,8,9

However I only want to print the middle line so I put但是我只想打印中间线所以我把

 with open('Book8.csv') as fp:
for line in fp:
    print line[1]

This gives me这给了我

, , as my output. , , 作为我的输出。

I want the output to be 4,5,6.我希望输出为 4,5,6。 It seems the commas or the [1] character in each line is being treated as part of the line.似乎每行中的逗号或 [1] 字符都被视为该行的一部分。 I'm not sure how to fix this.我不知道如何解决这个问题。

Eventually I'm going to want to do a regular expression on each of these lines to search for multiple substrings in each line.最终,我要在每一行上做一个正则表达式来搜索每一行中的多个子字符串。

For example:例如:

Line 1: There is text I want in here that text is _:E28, _:K31 blah blah第 1 行:这里有我想要的文字,文字是 _:E28、_:K31 等等

Line 2: There is text I want in here that text is _:H27, _:K12 blah blah第 2 行:这里有我想要的文字,文字是 _:H27、_:K12 等等

Will it be possible to write a regex to create a list for each line containing only my text of interest?是否可以编写一个正则表达式来为仅包含我感兴趣的文本的每一行创建一个列表?

For example: List 1=[" :E28", " :K31"] List 2=["_:H27", "_K12"]例如:列表 1=[" :E28", " :K31"] 列表 2=["_:H27", "_K12"]

Store your lines in a list and print from there.将您的行存储在列表中并从那里打印。 readlines() returns a list of every line in your file for you. readlines()为您返回文件中每一行的列表。

with open('Book8.csv') as fp:
    line = fp.readlines()

print(line[1])

You are iterating over the string at position 1 which is just ,您正在迭代位置 1 处的字符串,它只是,

import csv
with open ('Book8.csv','r') as csv_file:
    reader =csv.reader(csv_file)
    next(reader) # skip first row
    for row in reader:
        print(row)

As mentioned that you only want the middle row to get printed so you can use a simple row counter to actually count the rows and to only print the middle row如前所述,您只希望打印中间行,因此您可以使用简单的行计数器来实际计算行数并仅打印中间行

row_count = 0
with open('Book8.csv') as fp:
for line in fp:
    if row_count == 1:
        print line
    row_count+=1

If there is a case where there are multiple rows and you want all the middle rows to be printed except for the first and last one you can modify the code further如果存在多行并且您希望打印除第一行和最后一行之外的所有中间行的情况,您可以进一步修改代码

row_count = 0
with open('Book8.csv') as fp:
for line in fp:
    if row_count!=0 and row_count!=total_number_of_lines-1:
        print line
    row_count+=1

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

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