如何一行一行地读取文件,然后打印该行,如果它包含在Python中有一个值的范围的字符串? [英] How to read a file line by line, then print the line if it contains a string with a range of value in Python?
问题描述
我有一个文本文件,有一行行包含如下字符串:
AA ,, BB,2014-02-06,0,0 | CC ,, DD, 2014-02-27,0,0 | EE ,, FF,2014-02-04,1,1#GG#USD#true#Total:USD#1638.93#
(USD前有一堆文字,每行不同)。
我试着这样做:
打开('out_put_usjfk50.csv','rb'
reader = csv.reader(f,delimiter ='#')
读取器中的行:
amount = float(row [5])
如果amount <= 800 :
print row
elif amount is None:
pass
但我得到了相同的错误: ValueError:无法将字符串转换为浮动:
如何通过每一行来检查整数值(是字符串的一部分),然后打印行,如果它小于,比如USD1500?
您有一个CSV文件;请使用 csv
模块 :
import csv
with open('filename.csv','rb')as f :
reader = csv.reader(f,delimiter ='#')
读取器中的行:
新的每个 row
object是一个字符串列表;
说明'1638.93'
列是第8列, d使用(使用基于0的索引的Python):
amount = float(row [7])
现在你有一个浮点数字,你可以测试它:
with open('filename.csv','rb')as f:
reader = csv.reader(f,delimiter ='#')
for row in reader:
amount = float(row [7])
如果amount <= 1500:
打印行
I'm a newbie with Python 2.7 and I'm still trying to get the hang of it.
I have a text file with a row of lines that contain strings like this:
"AA,,BB,2014-02-06,0,0|CC,,DD,2014-02-27,0,0|EE,,FF,2014-02-04,1,1"#"GG"#"USD"#"true"#Total : USD#1638.93#
(There's a bunch of text before 'USD' that varies with each line.)
I tried doing this:
with open('out_put_usjfk50.csv', 'rb') as f:
reader = csv.reader(f, delimiter='#')
for row in reader:
amount = float(row[5])
if amount <= 800:
print row
elif amount is None:
pass
but I got the same error: ValueError: could not convert string to float:
I'm stumped. How do I go through each line to check for the integer value (that's part of a string), and then print the line(s) if it's less than, say, USD1500? I'd appreciate it if someone can point me to the right direction!
You have a CSV file; use the csv
module:
import csv
with open('filename.csv', 'rb') as f:
reader = csv.reader(f, delimiter='#')
for row in reader:
New each row
object is a list of strings; each string representing a column in your file.
Say the '1638.93'
column is column 8, then you'd use (with Python using 0-based indexing):
amount = float(row[7])
Now you have a floating point number from that string, and you can test against it:
with open('filename.csv', 'rb') as f:
reader = csv.reader(f, delimiter='#')
for row in reader:
amount = float(row[7])
if amount <= 1500:
print row
这篇关于如何一行一行地读取文件,然后打印该行,如果它包含在Python中有一个值的范围的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!