首页 > 解决方案 > Python中“AttributeError:'list'对象没有属性'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' object has no attribute 'split' 错误。

如果有人能指出我正确的方向,或者提出更好的方法,那就太好了。

标签: pythonparsingsplit

解决方案


利用:

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)

推荐阅读