AttributeError:'str'对象没有属性'readlines'

时间:2014-10-01 05:42:49

标签: string python-3.x attributeerror

我的代码出现问题。 我收到这个AttributeError,我不知道为什么。 有人提供一点见解,谢谢! 这是用python 3编写的, 我正试图制作一张图表。

import sys
data = {}
def main():
    filename = sys.argv[1]
    parseFile(filename)
    function()    
def parseFile(fn):
    print("Parsing", fn)
    infile = open(fn, "r")
    for line in infile:
        line = line[:-1]
        tokens = line.split()
        print(tokens)
        if line[0]=="#":
            line.readline() #<-- this is my problem line
        rsid = (tokens[0])
        genotype = (tokens[3])
        data[rsid] = genotype
    infile.close()
main()

# This data file generated by 23andMe at: Wed Jan 26 05:37:08 2011
#
# Below is a text version of your data. Fields are TAB-separated
# Each line corresponds to a single SNP.  For each SNP, we provide its identifier 
# (an rsid or an internal id), its location on the reference human genome, and the 
# genotype call oriented with respect to the plus strand on the human reference 
# sequence.     We are using reference human assembly build 36.  Note that it is possible 
# that data downloaded at different times may be different due to ongoing improvements 
# in our ability to call genotypes. More information about these changes can be found at:
# https://www.23andme.com/you/download/revisions/
# 
# More information on reference human assembly build 36:
# http://www.ncbi.nlm.nih.gov/projects/mapview/map_search.cgi?taxid=9606&build=36
#
# rsid  chromosome  position    genotype
rs4477212   1   72017   AA
rs3094315   1   742429  AA
rs1799883   1   742429  AA
rs3131972   1   742584  GG
rs12124819  1   766409  AA
rs11240777  1   788822  GG
rs6681049   1   789870  CC
rs4970383   1   828418  CC
rs4475691   1   836671  CC
rs7537756   1   844113  AA

1 个答案:

答案 0 :(得分:0)

属性错误意味着readline不是字符串方法。

在此代码段中:

for line in infile:
    line = line[:-1]
    tokens = line.split()

我猜(正确吗?)行[: - 1]是剥离换行符。如果是这种情况,请尝试这样做:

for line in infile:
    line = line.strip()
    tokens = line.split()

strip将剥离换行和回车。并且由于您只是将行更改为仅包含换行符的文本,因此您可以使用line.readline()删除行。

更新: 跳过以#

开头的行
for line in infile:
    line = line.strip()
    if line[0]=="#":
        continue
    tokens = line.split()

跳过&#34;跳过&#34;,我认为你想要忽略它们。

另外,为了获得良好的形式,你应该在你的parseFile函数中包含以下行:

def parseFile(fn):
    global data
    ...