如何通过文件存取将二维数组(对象)及c1-5值存入文本文件?
Hey there! Let's break down exactly how to fill in those gaps and get your data saved properly. The approach depends a bit on what you want the output file to look like (and how easy you want it to be to read later), so I'll cover a couple of common, straightforward methods.
Option 1: Custom Text Format (Simple, Human-Readable)
If you want a plain text file that's easy to scan manually, you can structure the content line by line. Here's a Python example (adjust the syntax for your language if needed):
# Assume you have these variables already defined c1 = 10 c2 = 20 c3 = 30 c4 = 40 c5 = 50 results = [15, 25, 35, 45, 55] two_d_array = [[1,2,3], [4,5,6], [7,8,9]] # Open a file in write mode ('w' overwrites, 'a' appends) with open('saved_data.txt', 'w') as file: # Write c1-c5 and their results file.write("c1-c5 Values & Results:\n") for idx, (c_val, res) in enumerate(zip([c1,c2,c3,c4,c5], results), 1): file.write(f"c{idx}: {c_val} | Result: {res}\n") # Write the 2D array file.write("\n2D Array:\n") for row in two_d_array: # Convert each row to a string (join elements with commas for readability) row_str = ', '.join(map(str, row)) file.write(f"{row_str}\n")
What's happening here:
- The
with open(...)block handles opening/closing the file safely (no need to remember to close it manually). - We first write a header for the c-values and results, then loop through pairs to write each line clearly.
- For the 2D array, we loop through each row, convert its elements to strings, join them with commas, and write each row as a separate line.
Option 2: JSON Format (Easy to Read/Programmatically Parse)
If you plan to load this data back into a program later, JSON is a great choice—it natively supports arrays and key-value pairs. Here's how to do it:
import json # Your existing data organized into a dictionary c_data = { "c1": {"value": 10, "result": 15}, "c2": {"value": 20, "result": 25}, "c3": {"value": 30, "result": 35}, "c4": {"value": 40, "result": 45}, "c5": {"value": 50, "result": 55} } two_d_array = [[1,2,3], [4,5,6], [7,8,9]] # Combine all data into a single structure for easy saving all_data = { "c_values_results": c_data, "2d_array": two_d_array } # Write to JSON file with pretty formatting with open('saved_data.json', 'w') as file: json.dump(all_data, file, indent=4) # indent=4 makes the file human-readable
Why this works:
- JSON converts your data into a standard text format that almost any programming language can parse later.
- The
indent=4parameter ensures the file isn't just a jumbled single line—you can open it in any text editor and read it easily. - To load the data back later, just use
json.load(open('saved_data.json'))and you'll get your original dictionary and array structure.
Option 3: CSV Format (Great for Tabular Data)
If your c-values and results are tabular and you want to use them with spreadsheets like Excel, CSV is perfect. Here's an example:
import csv # Your data c_names = ["c1", "c2", "c3", "c4", "c5"] c_values = [10,20,30,40,50] results = [15,25,35,45,55] two_d_array = [[1,2,3], [4,5,6], [7,8,9]] with open('saved_data.csv', 'w', newline='') as file: writer = csv.writer(file) # Write header for c-values and results writer.writerow(["Variable", "Value", "Result"]) # Write each c-value and its result as a row for name, val, res in zip(c_names, c_values, results): writer.writerow([name, val, res]) # Add a separator and header for the 2D array writer.writerow([]) writer.writerow(["2D Array Rows"]) # Write each row of the 2D array for row in two_d_array: writer.writerow(row)
Pick the option that fits your use case best—all of these will fill in the "blank" parts of your file-saving workflow!
内容的提问来源于stack exchange,提问作者Tae Min Kim

