You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Method 1: The csv.writer.writerows() expects a list of rows, where each row is a list of columns. When you pass x (a list of strings), it treats each string as a row of individual characters (since strings are iterable). With delimiter='\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.

  2. Method 2: You tried calling x.write(...), but x is a list, not a file object. The write() method belongs to open file handles, not lists. You need to open a file first and call write() on that file object instead.

  3. 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.

  4. Method 4: Here you're calling i.write(...) where i is a string from your list. Strings don't have a write() method—again, this is a method for file objects, not the data you're writing.

  5. Method 5: The variable number isn't defined anywhere in your code. You probably meant to loop through the items in x and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:44:46