如何从TXT文件读取文本并将逗号分隔内容拆分为单个元素存入Array
Hey there! Let's get this sorted for you. The main trick here is splitting the comma-separated text into individual elements once you read the file, instead of shoving the whole thing into a single array slot.
Step-by-Step Solution (Using Python as an example)
The core idea is: read the file → split the content by commas → clean up any extra whitespace around each item.
Here's a working code snippet:
# Safely read the content of your TXT file with open('your_file.txt', 'r') as text_file: # Read the entire content and strip any leading/trailing newlines/spaces file_content = text_file.read().strip() # Split the string by commas, then trim whitespace from each item target_array = [item.strip() for item in file_content.split(',')] # Check the result print(target_array) # Output: ['hello', 'school', 'tommy', 'house', 'homemaking']
Key Details:
file_content.split(','): This breaks the entire string into a list using commas as separators. Without cleaning, you'd get elements like" school"(with a leading space).item.strip(): This removes any leading/trailing spaces (or tabs/newlines) from each element, giving you clean, standalone words.- The
with open(...)syntax ensures the file is automatically closed after reading, which is good practice.
Bonus: Node.js Version
If you're working with JavaScript/Node.js, here's how you'd do it:
const fs = require('fs'); // Read the file as UTF-8 text fs.readFile('your_file.txt', 'utf8', (error, data) => { if (error) throw error; // Trim extra whitespace, split by commas, then clean each item const targetArray = data.trim().split(',').map(item => item.trim()); console.log(targetArray); // Output: ['hello', 'school', 'tommy', 'house', 'homemaking'] });
No matter which language you're using, the core logic stays the same: split the comma-separated string and clean up each element to get your desired array.
内容的提问来源于stack exchange,提问作者Cherry
相关产品推荐
相关产品推荐

