You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python的Pickle生成含递增列数据的指定格式文件?

Can You Use Pickle for This?

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 | PRICE lines 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:53:43