Python实现持续获取用户输入直至输入no并输出CSV及打印响应
Solution for Continuous User Input with CSV Output
Got it, here's a practical, easy-to-follow implementation that does exactly what you need—collects user input until they type "no", prints all responses to the console, and saves everything to a CSV file. Let's walk through it:
How It Works
- We'll use a loop to keep asking for input until the user enters "no" (case-insensitive, so "No" or "NO" works too)
- We'll store valid inputs in a list (ignoring empty entries to keep things clean)
- After input stops, we'll print all collected responses with numbered entries
- Finally, we'll write the data to a CSV file with a clear header for readability
Full Code Implementation
import csv # Initialize an empty list to store user's valid inputs user_responses = [] print("Start entering your text (type 'no' when you're done):") while True: # Get input and trim any leading/trailing whitespace current_input = input("> ").strip() # Check if user wants to exit the loop if current_input.lower() == "no": break # Only add non-empty inputs to our list if current_input: user_responses.append(current_input) else: print("Oops, empty input! Please enter some text or 'no' to stop.") # Print all collected responses to the console print("\n--- All Collected Responses ---") for count, response in enumerate(user_responses, start=1): print(f"{count}. {response}") # Write the responses to a CSV file if user_responses: # Use newline="" to avoid extra blank lines in CSV on Windows with open("user_responses.csv", "w", newline="", encoding="utf-8") as csv_file: csv_writer = csv.writer(csv_file) # Write a header row for clarity csv_writer.writerow(["Response ID", "Response Text"]) # Write each response as a separate row for count, response in enumerate(user_responses, start=1): csv_writer.writerow([count, response]) print("\n✅ Responses saved to user_responses.csv successfully!") else: print("\nℹ️ No valid responses collected, so no CSV file was created.")
Key Details to Note
- Case Insensitivity: Using
current_input.lower()ensures the exit condition works regardless of how the user capitalizes "no" - Empty Input Handling: We skip blank entries so your CSV doesn't have unnecessary empty rows
- UTF-8 Encoding: This ensures special characters (like accents or emojis) are saved correctly in the CSV
- Clean Console Output: Numbered responses make it easy to review what was entered
Alternative: Simplified CSV (No Header/ID)
If you prefer a simpler CSV with just one column of responses (no headers or IDs), replace the CSV writing section with this:
if user_responses: with open("user_responses.csv", "w", newline="", encoding="utf-8") as csv_file: csv_writer = csv.writer(csv_file) for response in user_responses: csv_writer.writerow([response]) print("\n✅ Responses saved to user_responses.csv successfully!")
内容的提问来源于stack exchange,提问作者sahmad
相关产品推荐
相关产品推荐

