如何用Python将CSV列中每个值保存为单独的CSV文件
Save Each CSV Column Value as a Separate File
Here's a straightforward, clean solution to create individual CSV files for each value in your column, building on your existing regex logic and using better file-handling practices:
Step-by-Step Code Implementation
import re # Use context managers to auto-handle file opening/closing (no more manual close() calls!) with open('test.csv', 'r') as test_file: # Skip the header line (the one with "----- label -----") next(test_file) # Iterate over each value line, keeping track of its position (index) for file_index, line in enumerate(test_file): # Clean the line using your original regex pattern to remove unwanted characters cleaned_value = re.sub('[^a-zA-Z0-9\n\.]', ' ', line).strip() # Name the output file after the line's index (0.csv, 1.csv, etc.) output_filename = f"{file_index}.csv" # Write the cleaned value to its own CSV file with open(output_filename, 'w') as output_file: output_file.write(cleaned_value)
Key Details & Adjustments:
- Context Managers (
withstatements): This is a Python best practice—it ensures files are properly closed automatically, even if an error occurs. No more forgettingtest_f.close()! - Header Skipping: The
next(test_file)call skips your header line so we only process the actual values (0, 1, 0, etc.). - Index-Based Filenames:
enumerate()gives us the position of each value (0 to 7 in your case), which we use to name the output files exactly as you need. - Cleaning Flexibility: If your values are only numbers, you can simplify the regex to
re.sub('[^0-9]', '', line).strip()to remove all non-digit characters directly.
What This Does:
- Creates 8 files:
0.csv,1.csv,2.csv, ...,7.csv - Each file contains just the cleaned value from the corresponding line in your input CSV.
内容的提问来源于stack exchange,提问作者Martin
相关产品推荐
相关产品推荐

