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

如何用Python从空格分隔的.DAT文件中提取多列?

Extract Columns from Space-Separated .DAT Files (For Beginners)

Hey there! Since you're new to programming and learning via Google searches, let's break this down into simple, actionable steps using Python—it's perfect for this kind of file processing task, and the code will be easy to follow and tweak.

Step 1: Prepare Python (If You Haven't Already)

If you don't have Python installed, grab the latest stable version from the official site (just make sure to check "Add Python to PATH" during setup—this makes it easier to run code later). Once installed, open a text editor like Notepad, VS Code, or Python's built-in IDLE to write your script.

Step 2: Code to Process a Single .DAT File

Let's start with one file first, then scale to all 38. This code reads your .DAT file, extracts metadata and data columns, and saves the result to a CSV file (which is easy to open in Excel or Google Sheets):

# Open your .DAT file (replace 'your_file.dat' with your actual file name)
with open('your_file.dat', 'r') as file:
    # Read all content and split into individual parts (split by spaces)
    all_content = file.read().split()

# Extract metadata from the start of the file
ngano = all_content[all_content.index('NGANo:') + 1]
zeta = float(all_content[all_content.index('Zeta:') + 1])
ds5_95 = float(all_content[all_content.index('Ds5-95:') + 1])

# Find the start of the column names (after "Comments:")
comments_index = all_content.index('Comments:')
column_names = all_content[comments_index + 1].split(',')  # Split "Period,SD,SV,SA" into a list
# Clean up any extra spaces in column names
column_names = [name.strip() for name in column_names]

# The rest of the content is the data values
data_values = all_content[comments_index + 2:]
# Split values into groups of 4 (matching your example's 4 columns per row)
data_rows = [data_values[i:i+4] for i in range(0, len(data_values), 4)]
# Convert values to floats for easier analysis
data_rows = [[float(val) for val in row] for row in data_rows]

# Save results to a CSV file
import csv

with open('extracted_data.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # Write metadata as header rows (optional but helpful for context)
    writer.writerow(['NGANo', ngano])
    writer.writerow(['Zeta', zeta])
    writer.writerow(['Ds5-95', ds5_95])
    writer.writerow([])  # Empty row for spacing
    # Write column headers
    writer.writerow(column_names)
    # Write all data rows
    writer.writerows(data_rows)

print("Done! Check extracted_data.csv for your results.")

Step 3: Scale to All 38 .DAT Files

To process every file at once, we'll use Python's os module to loop through all .DAT files in a folder. Here's the adjusted code:

import os
import csv

# Set the folder where your .DAT files are stored (replace with your actual folder path)
folder_path = 'path/to/your/dat/files'

# Create a folder to store extracted CSV files (avoids clutter)
output_folder = 'extracted_csvs'
os.makedirs(output_folder, exist_ok=True)

# Loop through each .DAT file in the folder
for filename in os.listdir(folder_path):
    if filename.lower().endswith('.dat'):
        file_path = os.path.join(folder_path, filename)
        print(f"Processing {filename}...")

        # Reuse the same processing logic as before
        with open(file_path, 'r') as file:
            all_content = file.read().split()

        ngano = all_content[all_content.index('NGANo:') + 1]
        zeta = float(all_content[all_content.index('Zeta:') + 1])
        ds5_95 = float(all_content[all_content.index('Ds5-95:') + 1])

        comments_index = all_content.index('Comments:')
        column_names = all_content[comments_index + 1].split(',')
        column_names = [name.strip() for name in column_names]

        data_values = all_content[comments_index + 2:]
        data_rows = [data_values[i:i+4] for i in range(0, len(data_values), 4)]
        data_rows = [[float(val) for val in row] for row in data_rows]

        # Save to a CSV with the same name as the original .DAT file
        output_filename = os.path.splitext(filename)[0] + '.csv'
        output_path = os.path.join(output_folder, output_filename)

        with open(output_path, 'w', newline='') as csv_file:
            writer = csv.writer(csv_file)
            writer.writerow(['NGANo', ngano])
            writer.writerow(['Zeta', zeta])
            writer.writerow(['Ds5-95', ds5_95])
            writer.writerow([])
            writer.writerow(column_names)
            writer.writerows(data_rows)

print("All files processed! Check the extracted_csvs folder for your results.")

Quick Tips for You:

  • If you put all .DAT files in the same folder as your Python script, use folder_path = '.' (this means "current folder") instead of typing a full path.
  • This code assumes every .DAT file has the same structure as your example. If some files have different column counts or metadata fields, we can tweak the code—just let us know!
  • CSV files are perfect for later analysis, whether you want to use spreadsheets or do more programming with the data.

内容的提问来源于stack exchange,提问作者user9749709

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:45:45