如果行包含特定字符串,请定义CSV文件的行 [英] Define row of CSV file if row contains specific string
问题描述
我一直在学习Python两个星期,在Python中阅读和写入CSV文件时,我想知道一些事情。
我使用了 def
输出代码:
def csv(filename):
f = open文件名,'rU')
lines = []
for f:
lines.append(line.rstrip('\\\
')。split b $ b f.close()
返回行
例如:
[['a','','','','','']
['b','','','','',''],
['c ','','','','',''],
< ''],
['e','','','','',''],
['f','','','','',''],
['g','', ','','','']]
假设我想更改包含'a'
。
我可以使用哪些代码来定义 a
?
首先,使用 built-in csv parser 。
此代码将定义一个包含'a'的行的Python列表:
import csv
rows = csv.reader(open('yourfile.csv','rb'),delimiter ='',quotechar ='|')
arows = [行中的行,如果行中有'a']
I've been studying Python for two weeks and there's something I want to know when reading and writing CSV file in Python.
I used def
codes for output:
def csv(filename):
f = open(filename, 'rU')
lines = []
for line in f:
lines.append(line.rstrip('\n').split(','))
f.close()
return lines
And the result from above codes looks like:
[['a', '', '', '', '', ''],
['b', '', '', '', '', ''],
['c', '', '', '', '', ''],
['d', '', '', '', '', ''],
['e', '', '', '', '', ''],
['f', '', '', '', '', ''],
['g', '', '', '', '', '']]
Let's say I want to change the value of first row that contains 'a'
.
What codes can I use to define the row containing a
?
First, use built-in csv parser.
This code will define a python list of rows which contains 'a':
import csv
rows = csv.reader(open('yourfile.csv', 'rb'), delimiter=' ', quotechar='|')
arows = [row for row in rows if 'a' in row]
这篇关于如果行包含特定字符串,请定义CSV文件的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!