python - 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' 错误。
如果有人能指出我正确的方向,或者提出更好的方法,那就太好了。
解决方案
利用:
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)
推荐阅读
- r - R中数据帧的特殊过滤
- vba - 将 uid 和 pwd 文件调用到系统 dsn 的访问数据库中
- c - c中fseek函数中的origin参数
- excel - 如何将数据从sheet1中的单元格复制到sheet2,循环遍历每个单元格?
- postgresql - 使用 pgcrypto 存储在 postgres 中加密的某些字段
- linux - 带有捕获信号的 shell 脚本不会忽略信号
- dataframe - 在数据帧上使用 ipywidgets SelectMultiple
- c - C - 为什么我的代码在删除未使用的变量声明时会中断
- python - 列表项之间的无意串联
- python - 如何替换pyspark数据框中的非ASCII字符