如何提取字母Y之后的字符串并写入CSV文件?
提取每行Y之后内容的CSV转换代码
Hey there, I see you need to tweak your existing text-to-CSV script to only grab the parts of each line that come after the letter "Y". Let's adjust that code to do exactly what you need:
import csv txt_file = r"input.txt" csv_file = r"Good_data.csv" # Use context managers to handle files safely (no need to manually close them) with open(txt_file, "r") as infile, open(csv_file, 'w', newline='') as outfile: reader = csv.reader(infile, delimiter=',') writer = csv.writer(outfile) for row in reader: processed_cells = [] for cell in row: # Find the first position of "Y" in the cell y_pos = cell.find('Y') if y_pos != -1: # Extract everything after Y, and trim extra whitespace extracted = cell[y_pos + 1:].strip() processed_cells.append(extracted) else: # If there's no Y in the cell, keep the original content (trimmed) processed_cells.append(cell.strip()) # Write the processed row to CSV writer.writerow(processed_cells)
Key changes and explanations:
- Safe file handling: Used
withstatements to open files—this ensures files are automatically closed when we're done, avoiding resource leaks. - Per-cell processing: Instead of writing rows directly, we loop through each cell in the row to find and extract content after the first "Y".
- Whitespace cleanup: Added
.strip()to remove any leading/trailing spaces from the extracted content (like the space beforeY'ay' TQin your example, which becomes'ay' TQafter processing). - Fallback for no Y: If a cell doesn't contain "Y", it just keeps the original trimmed content (you can change this to skip the cell entirely by replacing
processed_cells.append(cell.strip())withpassif that's what you need).
For your example input line:
u'gY': -0.009,Y'gm': 0.0011, Y'ay' TQ
The processed CSV row will be:: -0.009, 'gm': 0.0011, 'ay' TQ
内容的提问来源于stack exchange,提问作者John steven
相关产品推荐
相关产品推荐

