Python中的“ AttributeError:'列表'对象没有属性'split'”问题

时间:2019-06-19 11:32:19

标签: python parsing split

我是Python的新手,我试图找出对我来说是解析文本文件中某些信息的最佳方法。

给定文件的外观如下:

#
0.010000 125 _
0.130000 125 d
0.225000 125 o
0.260000 125 b
0.275000 125 a
0.335000 125 r
0.400000 125 v
0.455000 125 a
0.530000 125 m
0.580000 125 d

#标志着文件的开头。
我想在每一行中制作三个变量。对于第一行,它看起来像这样:

x = 0.010000  
y = 125  
z = "_" 

因为我正在使用tkinter,所以当前代码如下:

    def cutFile(fileAudio, fileTime):
        path = fileAudio.get()
        fileAudioName = os.path.split(path)[1]
        pathTime = fileTime.get()
        fileTimeName = os.path.split(pathTime)[1]
        sound_file = AudioSegment.from_mp3(fileAudioName)
        timeFile = open(pathTime, "r")
        line = timeFile.readlines()
        newLine = line.split("\n")
        for i in range(1, len(newLine)):
            x, y, z = newLine.split(" ")
            print(z)

问题似乎已经开始了

    newLine = line.split("\n")

因为我遇到AttributeError:'list'对象没有属性'split'错误。

如果有人能指出我正确的方向,或提出更好的方法,那将非常好。

2 个答案:

答案 0 :(得分:0)

尝试一下:

lines = timeFile.readlines()
for x, l in enumerate(lines):
    if l.strip() == '#':
        break
else
    raise TypeError("invalid file content, missing '#' line")

for i in range(x + 1, len(lines), 1):
    l = lines[i]
    x, y, z = l.split()
    print(z)

这是怎么回事?打开后,您可以通过调用timeFile.readlines()来读取文件。这会返回列表行。因此,我们首先寻找仅包含#的“开始”行。我们去除空格,因为我们通常不希望处理空格,并且“#”和“#”看起来几乎相同,并且容易丢失手工编辑的文件。找到该行之后,我们从下一个迭代到文件末尾,对于l的每一行,我们通过调用split()进行拆分并打印z

答案 1 :(得分:0)

使用:

with open(pathTime) as infile:                #Open file for read
    next(infile)   #Skip #                   
    for line in infile:                       #Iterate Each line
        x, y, z = line.strip().split(" ")     #Strip leading and trailing space and split
        print(x, y, z)

输出:

0.010000 125 _
0.130000 125 d
0.225000 125 o
0.260000 125 b
0.275000 125 a
0.335000 125 r
0.400000 125 v
0.455000 125 a
0.530000 125 m
0.580000 125 d

在您的代码中,您不需要newLine = line.split("\n"),因为readlines()已经按\n分割了文件内容

例如:

timeFile = open(filename, "r")
lines = timeFile.readlines()

for line in lines[1:]:
    x, y, z = line.strip().split(" ")
    print(z)