Python列表写入文本文件的最优方法及常见报错解决
Hey there! Let's walk through what's wrong with each of your writing methods, then show you the cleanest ways to get this done—including a much simpler approach using pandas since you already imported it.
First, a quick note on your extraction code
Wait, one thing to double-check: i.split()[3] grabs the 4th column (since Python uses 0-based indexing). If you actually need the 3rd column, you should use i.split()[2] instead. Just wanted to flag that to avoid column mix-ups!
Why each method failed
Method 1: The
csv.writer.writerows()expects a list of rows, where each row is a list of columns. When you passx(a list of strings), it treats each string as a row of individual characters (since strings are iterable). Withdelimiter='\n', this splits each character onto its own line, which is why you see split-up digits. You could fix this by wrapping each item in a list (writer.writerows([[item] for item in x])), but using csv for this is overkill—plain file writing is simpler.Method 2: You tried calling
x.write(...), butxis a list, not a file object. Thewrite()method belongs to open file handles, not lists. You need to open a file first and callwrite()on that file object instead.Method 3:
str(x)converts your entire list into a single string (e.g.,['1.23', '4.56']becomes"['1.23', '4.56']"). Writing this directly puts everything on one line with commas, which isn't what you want for a single-column file.Method 4: Here you're calling
i.write(...)whereiis a string from your list. Strings don't have awrite()method—again, this is a method for file objects, not the data you're writing.Method 5: The variable
numberisn't defined anywhere in your code. You probably meant to loop through the items inxand write each one, but forgot to reference the loop variable.
Optimal Solutions
Option 1: Plain Python (no pandas)
This is straightforward and efficient for small to medium files:
import os # First, fix the extraction (adjust index to 2 if you need the 3rd column) myfile = "your_input_file.txt" output_path = "x.txt" x = [] # Use with-statement to auto-close the file (safer than manual close()) with open(myfile, "r") as f: for line in f: stripped_line = line.strip() if stripped_line: # Skip empty lines parts = stripped_line.split() x.append(parts[3]) # 4th column; use parts[2] for 3rd # Write to output file efficiently with open(output_path, "w") as f: # Join all items with newlines, add a final newline for clean formatting f.write("\n".join(x) + "\n") # Or if you prefer line-by-line writing (slower for large files but readable) # with open(output_path, "w") as f: # for item in x: # f.write(f"{item}\n")
Option 2: Use pandas (way simpler for multi-column tasks)
Since you already imported pandas, let's leverage it—especially useful if you need to write all 7 columns to separate files later:
import pandas as pd import os myfile = "your_input_file.txt" # Read the space-separated file (no headers) df = pd.read_csv(myfile, sep="\s+", header=None) # Write the 4th column (index 3) to x.txt (adjust to 2 for 3rd column) df[3].to_csv("x.txt", index=False, header=False) # Bonus: Write ALL 7 columns to separate files in one go! for col_index in range(df.shape[1]): # Name files like column1.txt, column2.txt, etc. output_file = f"column{col_index + 1}.txt" df[col_index].to_csv(output_file, index=False, header=False)
This handles edge cases like inconsistent spacing between columns, empty lines, and formatting automatically—saving you way more time than debugging manual splits and writes.
内容的提问来源于stack exchange,提问作者FabioSpaghetti

