如何使用Python的Pickle生成含递增列数据的指定格式文件?
Absolutely—but let’s clarify a key point first: Pickle is designed to serialize Python objects (like lists, tuples, or dictionaries) so you can load them back into Python later. It doesn’t create human-readable text files in the CODE | PIECE | PRICE format you described.
If your main goal is to store the data for future use in Python, pickle works perfectly. If you want a plain text file with that exact line structure, you’ll want to write directly to a text file instead. Let’s cover both scenarios:
1. Using Pickle to Store Data (For Python Later Use)
First, we’ll create a structured dataset (a list of tuples) and save it with pickle. This lets you reload the exact data structure into Python anytime.
import pickle # Generate the dataset from 1 to 50 data = [] for i in range(1, 51): code = i piece = i price = f"{i},00" # Format price with comma decimal data.append((code, piece, price)) # Save the data to a pickle file with open('inventory_data.pkl', 'wb') as f: pickle.dump(data, f) # To load the data back later: # with open('inventory_data.pkl', 'rb') as f: # loaded_data = pickle.load(f) # print(loaded_data) # Outputs the full list of tuples
2. Creating the Human-Readable Text File (Your Desired Format)
If you need a file with lines like 1 | 1 | 1,00, pickle isn’t the right tool. Instead, write directly to a text file:
# Generate and write to a text file with open('inventory.txt', 'w') as f: # Write the header line f.write("CODE | PIECE | PRICE\n") # Write each data row for i in range(1, 51): line = f"{i} | {i} | {i},00\n" f.write(line)
This creates a text file that’s readable in any text editor, matching your exact format.
Bonus: Do Both at Once
If you need both the pickle file (for Python use) and the text file (for readability), combine the two steps:
import pickle # Generate the dataset data = [] for i in range(1, 51): data.append((i, i, f"{i},00")) # Save to pickle with open('inventory_data.pkl', 'wb') as f: pickle.dump(data, f) # Save to text file with open('inventory.txt', 'w') as f: f.write("CODE | PIECE | PRICE\n") for row in data: f.write(f"{row[0]} | {row[1]} | {row[2]}\n")
Quick Reminder
- Pickle files are binary, so you can’t open them in a text editor to see the
CODE | PIECE | PRICElines directly—they’re only for Python-to-Python data transfer. - If you need compatibility with other programs or human readability, stick to the text file approach (or use CSV for more structured tabular data).
内容的提问来源于stack exchange,提问作者David

