Python中出现AttributeError: 'list' object has no attribute 'split'错误的解决咨询
Hey there! Let's work through your problem step by step.
First, the error you're seeing (AttributeError: 'list' object has no attribute 'split') makes perfect sense: when you call timeFile.readlines(), it returns a list where each element is a single line from your file (including the newline character \n at the end of most lines). You can't call .split("\n") on a list—this method only works on strings.
Let's fix that, plus clean up the code to be more robust (especially since you're using Tkinter, we want things to be reliable):
Here's a revised version of your function
import os from pydub import AudioSegment def cutFile(fileAudio, fileTime): path = fileAudio.get() fileAudioName = os.path.split(path)[1] pathTime = fileTime.get() # Use a `with` statement to handle the file—it auto-closes when done, which is safer sound_file = AudioSegment.from_mp3(fileAudioName) with open(pathTime, "r") as timeFile: # Iterate over each line directly (no need for readlines() unless you need to store all lines first) for line_num, line in enumerate(timeFile): # Strip whitespace (including newlines) from the start/end of the line cleaned_line = line.strip() # Skip empty lines and the header line starting with # if not cleaned_line or cleaned_line.startswith("#"): continue # Split the line into parts—using split() without arguments handles any number of spaces/tabs parts = cleaned_line.split() # Make sure we have exactly 3 parts before unpacking (avoids ValueError) if len(parts) == 3: x, y, z = parts # Convert x and y to appropriate types (float and int) since they're numbers x = float(x) y = int(y) print(f"x: {x}, y: {y}, z: {z}") else: print(f"Skipping malformed line {line_num + 1}: {cleaned_line}")
Key improvements & fixes:
- Fixed the broken split: Instead of reading all lines into a list first, we iterate directly over the file object (more memory-efficient for large files) and clean each line individually.
- Handled the header line: We skip any line starting with
#and empty lines to avoid parsing errors. - Safer splitting: Using
split()(no arguments) splits on any whitespace (spaces, tabs, etc.), which is better thansplit(" ")—it won't create empty string elements if there are multiple spaces between values. - Type conversion: We convert
xto a float andyto an int since they're numeric values (your original code would leave them as strings, which might cause issues later). - Error handling: We check that each line has exactly 3 parts before unpacking, so malformed lines won't crash your program—they'll just get skipped with a message.
- Auto-closing files: The
withstatement ensures the file is closed properly even if an error occurs, which is a best practice in Python.
This should resolve your AttributeError and make your text parsing much more reliable. Let me know if you run into any other issues!
内容的提问来源于stack exchange,提问作者JohnC

