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

Python开发ZRC代币模拟系统:解决文本文件浮点数读写与间隔更新问题

Hey there! Let's work through your ZRC simulation program issues step by step. I'll break down each problem, explain why it's happening, and show you how to fix it—plus share a revised version of your code that addresses all your concerns.

Problem 1: Can't correctly import the float token value from the file

The main issue here is that when you read from Token.txt, there might be hidden whitespace (like newlines, spaces, or tabs) left over from previous writes. Trying to convert that messy string directly to a float will throw an error.

Fix: Use .strip() to clean up any extra whitespace when reading the file. This ensures you're only converting the actual number string to a float.

Problem 2: Extra spaces appearing before the number when updating Token.txt

This happens because of how you're using truncate(0) without resetting the file pointer. When you open the file in r+ mode, the pointer moves as you read/write. If you truncate without moving the pointer back to the start first, you might leave leftover characters from longer previous values (like spaces) in the file.

Fix: Before truncating, use seek(0) to jump to the start of the file. Then truncate, write the new value, and flush to ensure the change is saved immediately.

Problem 3: Ensuring the program reads the last value on every run

This ties into the first two fixes—if reading/writing is done cleanly, each run will pick up the last saved token. We'll also add a safety check to create the file with 1.0 if it doesn't exist (for the initial state).


Revised Full Code

import time
import random
import decimal
import os

userUSD = 0
tokenInterval = 2

def user():
    print('Running as User...\n')
    # Handle USD input with validation to avoid non-numeric entries
    while True:
        try:
            userUSD = float(input('USD Input: '))
            break
        except ValueError:
            print("Oops, please enter a valid number for USD!")
    ZRC = userUSD  # Assuming 1 USD = 1 ZRC initially
    print(f'USD: {userUSD:.2f} is now equal to ZRC: {ZRC:.2f}')
    invest(ZRC)

def invest(ZRCl):
    global token
    # Validate time input to avoid invalid values
    while True:
        try:
            seconds = int(input('\nRepeat for time (seconds): '))
            if seconds < 0:
                print("Please enter a non-negative number for time.")
                continue
            break
        except ValueError:
            print("Oops, please enter a valid integer for time!")
    
    print('Running Investment...\n\n')
    # Use 'with' statement for auto file closing (better practice)
    with open("Token.txt", "r+") as tokenFW:
        start = time.time()
        ZRCf = format(ZRCl, ".4f")  # Initialize to avoid NameError if loop doesn't run
        while time.time() - start < seconds:
            time.sleep(tokenInterval)
            upordown = random.randint(0,5)
            step = float(decimal.Decimal(random.randrange(0,10000))/1000000000)
            
            # Update token and keep it within your 0.8-1.2 range
            if upordown in (1, 2):
                token += step
                token = min(max(token, 0.8), 1.2)
            elif upordown in (4,5):
                token -= step
                token = min(max(token, 0.8), 1.2)
            # upordown ==3 does nothing, so we can skip the 'pass'
            
            ZRCl *= token
            ZRCf = format(ZRCl, ".4f")
            
            # Fix file writing flow: jump to start → clear content → write new value
            tokenFW.seek(0)
            tokenFW.truncate(0)
            tokenFW.write(f"{token:.10f}")
            tokenFW.flush()  # Ensure the write is saved immediately
            
            print(f'Token: {token:.10f}')
            print(f'New ZRC Amount: {ZRCf}\n')
        
        print('Investment End')
        print(f'Final New ZRC Amount: {ZRCf}')

# Initialize token from file (or create file with 1.0 if it doesn't exist)
token_file_path = "Token.txt"
if not os.path.exists(token_file_path):
    with open(token_file_path, "w") as f:
        f.write("1.0")
    token = 1.0
else:
    with open(token_file_path, "r") as tokenF:
        token_str = tokenF.read().strip()
        try:
            token = float(token_str)
        except ValueError:
            print(f"Invalid value in Token.txt: {token_str}. Resetting to 1.0.")
            with open(token_file_path, "w") as f:
                f.write("1.0")
            token = 1.0

user()

Key Improvements Explained

  1. Robust File Handling:

    • Added a check to create Token.txt with 1.0 if it doesn't exist (covers your initial state requirement).
    • Used .strip() when reading to eliminate whitespace issues.
    • The seek(0) → truncate(0) → write() flow ensures no leftover characters in the file.
    • with statements auto-close files, preventing resource leaks even if the program crashes.
  2. Input Validation:

    • Added loops with try/except to handle invalid user input (like non-numeric USD or negative time values), making the program more user-friendly.
  3. Token Range Enforcement:

    • Added min(max(token, 0.8), 1.2) to keep the token within your specified 0.8-1.2 range, as mentioned in your problem description.
  4. Cleaner Formatting:

    • Used f-strings for more readable string formatting instead of concatenation.
    • Initialized ZRCf before the loop to avoid a NameError if the user enters 0 seconds.

内容的提问来源于stack exchange,提问作者Zer0 - Official

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 15:02:48