如何通过循环处理CSV文件,将第三列值为0的行移至首行
Solution to Move Specific CSV Records to the Front
Got it, let's work through this problem. Based on your input example (where each record is a quoted triple separated by spaces) and requirements, here's a practical Python solution that does exactly what you need:
# Replace these with your actual file paths input_file = "your_input.csv" output_file = "your_output.csv" # Read the entire file content and clean up leading/trailing whitespace with open(input_file, 'r') as f: raw_content = f.read().strip() # Split content into individual records, filtering out empty strings from extra spaces records = [record for record in raw_content.split(' ') if record] # Separate records where the third field is "0" from the rest zero_records = [] remaining_records = [] for record in records: # Split the record into its three fields (strip surrounding quotes first) fields = record.strip('"').split('","') # Check if the third field is exactly "0" (you noted other fields won't have "0", so no false matches) if fields[2] == "0": zero_records.append(record) else: remaining_records.append(record) # Combine the records: zero-containing ones first, followed by the rest final_content = ' '.join(zero_records + remaining_records) # Write the result to the output file with open(output_file, 'w') as f: f.write(final_content)
How this works:
- Read and clean content: We read the entire file at once, stripping any leading/trailing whitespace to avoid issues with extra spaces at the start/end of the file.
- Split into records: We split the content using spaces as separators, and filter out any empty strings that might come from consecutive spaces.
- Sort records: For each record, we strip the surrounding quotes and split it into its three fields using
","as the delimiter. Since you confirmed no other fields will have "0", we can safely check if the third field equals "0" to identify the target records. - Combine and write: We concatenate the target records (with "0" in the third field) followed by all other records, then write the combined string back to a file.
If your file actually has one record per line instead of all in a single line, you can adjust the code slightly to process lines instead of splitting by spaces—just let me know if you need that variation!
内容的提问来源于stack exchange,提问作者Alper Köse
相关产品推荐
相关产品推荐

