![](/img/trans.png)
[英]Why in python loop for line in file is not going through all lines after using readline before?
[英]move through lines after using readline() python
我目前正在尝试使用python的csv模块解析两种不同类型的文件。 为了发现我要解析的文件,我必须阅读第二行的第一个字母。 根据该行的内容,我想移至第7行或第4行,然后使用csv读取数据。 我读到在文件对象上混合readline()和next()无效。 下线有其他方法吗? 这是我当前的代码,可以更好地了解我的尝试:
with open(str(new_file)) as new_file:
new_file.next()
line2 = new_file.readline()
# Check to see which file it is
if line2[0] == "P":
# Move to line 7
else:
# Move to line 4
# Read in the contents of the file and get rid of whitespace
list_of_dicts = list(csv.DictReader(new_file, delimiter = " ", skipinitialspace = True))
如果有人对如何解决这个问题有一个想法,那就太好了。
line2 = new_file.next() # now pointing at line 3
if line2[0] == "P":
for _ in xrange(4):
new_file.next() # skip lines 3, 4, 5, 6
else:
new_file.next() # skip line 3 only
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.